【发布时间】:2018-12-31 21:22:00
【问题描述】:
当想用 Jest 模拟外部模块时,我们可以使用 jest.mock() 方法在模块上自动模拟函数。
然后我们可以随意操作和询问模拟模块上的模拟函数。
例如,考虑以下模拟 axios 模块的人为示例:
import myModuleThatCallsAxios from '../myModule';
import axios from 'axios';
jest.mock('axios');
it('Calls the GET method as expected', async () => {
const expectedResult: string = 'result';
axios.get.mockReturnValueOnce({ data: expectedResult });
const result = await myModuleThatCallsAxios.makeGetRequest();
expect(axios.get).toHaveBeenCalled();
expect(result).toBe(expectedResult);
});
以上在 Jest 中运行良好,但会抛出 Typescript 错误:
类型 '(url: 字符串,配置?:AxiosRequestConfig | undefined) => AxiosPromise'.
axios.get 的 typedef 正确地不包括 mockReturnValueOnce 属性。我们可以通过将 axios.get 包装为 Object(axios.get) 来强制 Typescript 将其视为 Object 字面量,但是:
在保持类型安全的同时模拟函数的惯用方法是什么?
【问题讨论】:
-
也许另一种方法是使用像
axios.get = jest.fn()这样的赋值,即github.com/dvallin/vuejs-tutorial/blob/…
标签: node.js reactjs typescript mocking jestjs