我有一个具有以下依赖项的React组件:
import { fetchUsers } from '../../api/';
这是返回Promise的实用程序函数。
当试图使用Jest模拟这个时,我无法在describe()
的每个测试基础上执行此操作。
我能够模仿fetchUsers
的唯一方法是将jest.mock()
放在整个测试套件的文件顶部。
import x from './x'
jest.mock('../../../../src/api/', () => ({
fetchUsers: jest.fn(() => Promise.resolve({ users: [] })),
}));
这不适合我需要在不同的测试中测试.then()
(Promise.resolve)和.catch
(Promise.reject)。有了上述,我只能测试.then()
有谁知道如何使用Jest来模拟React Component的依赖项,该依赖项在每个测试的基础上返回一个promise?
谢谢
Jest模拟函数可以改变实现:
jest.mock('../../../../src/api/', () => ({
fetchUsers: jest.fn()
}));
...
const { fetchUsers } = require('../../../../src/api/');
fetchUsers.mockImplementation(() => Promise.resolve({ users: [] }));
// do something that calls fetchUsers
正如在this answer中所解释的那样,由于ES模块的工作方式,也可以随时在转换的*
导入上模拟属性:
import * as api from '../../../../src/api/';
...
jest.spyOn(api, 'fetchUsers').mockImplementation(() => Promise.resolve({ users: [] }));
// do something that calls fetchUsers