我有一个假设file.js的代码是这样的
const myFunc = () => {
return {
func1: () => {},
func2: () => {}
}
}
export const myObject = {
key: ''
};
export default myFunc();我正试图在我的测试中使用jest模拟这个导出。假设file.test.js是测试文件。
jest.mock('./path/file', () => {
return {
default: {
func1: jest.fn(),
func2: jest.fn()
},
myObject: {}
};
});但是当我的测试运行时,它抛出错误,说_File.default.func1 is not a function。
如何正确地模拟同时具有默认导出和命名导出的js文件?
发布于 2020-09-29 15:05:57
解决方案:
index.ts
const myFunc = () => {
return {
func1: () => {},
func2: () => {},
};
};
export const myObject = {
key: '',
};
export default myFunc();index.test.ts
import fns, { myObject } from './';
jest.mock('./', () => {
return {
myObject: { key: 'teresa teng' },
func1: jest.fn(),
func2: jest.fn(),
};
});
describe('64003254', () => {
it('should pass', () => {
expect(jest.isMockFunction(fns.func1)).toBeTruthy();
expect(jest.isMockFunction(fns.func2)).toBeTruthy();
expect(myObject.key).toBe('teresa teng');
});
});单元测试结果:
PASS src/stackoverflow/64003254/index.test.ts (11.809s)
64003254
✓ should pass (6ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 13.572shttps://stackoverflow.com/questions/64003254
复制相似问题