我可以说file.js具有类似这样的代码
const myFunc = () => {
return {
func1: () => {},
func2: () => {}
}
}
export const myObject = {
key: ''
};
export default myFunc();
我试图在测试中使用玩笑来模拟此导出。可以说file.test.js是测试文件。
jest.mock('./path/file', () => {
return {
default: {
func1: jest.fn(),
func2: jest.fn()
},
myObject: {}
};
});
但是,当我的测试正在运行时,会抛出错误_File.default.func1 is not a function
。
如何正确模拟同时具有默认出口和命名出口的js文件?
答案 0 :(得分:0)
解决方案:
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.572s