我似乎无法使 mock 正常工作。
一些上下文:
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"
storage.ts 包含一个方法
getOsTmpDir
.moduleA.ts 正在消耗 storage.ts
在 moduleA.spec.ts 中:
jest.mock('./storage', () => ({
getOsTmpDir: jest.fn().mockImplementation(() => '/tmp'),
}));
打印(在 console.log(getOsTmpDir());
中给出 undefined
我尝试过的其他事情:
-
getOsTmpDir: jest.fn(() => '/tmp')
-
getOsTmpDir: jest.fn().mockReturnValue('/tmp')
但似乎没有任何帮助。我错过了什么?
编辑:我发现了问题。我没有注意到所有模拟在每次测试前都被重置,因为我已经在文件顶部定义了模拟(一次) ,模拟在运行任何测试之前终止
beforeEach(async () => {
jest.resetAllMocks(); <----
....
}
最佳答案
您如何导出/导入该方法?这是模拟导出函数时的样子:
定义“真实”函数:
~fileA.ts
...
export function what() {
console.log('A');
}
...
测试:
~test.ts
...
import { what } from './fileA';
jest.mock('./fileA', () => ({
what: jest.fn().mockImplementation(() => console.log('B')),
}));
describe('mocks', () => {
it('should work', () => {
what();
});
});
$ jest test.ts
...
console.log test.ts:9
B
您应该看到测试调用了what
的模拟实现并记录了 B。
关于typescript - Jest mock 总是给出 undefined (typescript + ts-jest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357953/