当我使用 TypeScript 编译器编译我的测试并使用 Jest 模拟时,我经常收到来自 tsc
的错误。喜欢:
error TS2339: Property 'mockImplementationOnce' does not exist on type
'typeof readFile'.
从这个最小测试:
jest.mock('fs');
// Run before the imports but does not alter types :(
import { readFile } from 'fs';
import { fnThatReadsFile } from './lib';
it('should read a file', () => {
const err = {};
readFile.mockImplementationOnce((_, callback) => callback(err, null));
// ^^ error TS2339: Property 'mockImplementationOnce' does not exist on type 'typeof readFile'.
fnThatReadsFile();
// expect...
});
除了:
- 选角:
readFile as jest.Mock<{}>
- module augmentation
当 jest.mock
需要模块时,TypeScript 插件能否执行模块扩充? ?
最佳答案
最简单的解决方案是像这样导入 fs:const fs = require('fs')
,并使用 (fs.readFile as jest.Mock).mockImplementationOnce ...
关于unit-testing - 使用 jest.mock 和 TypeScript 而无需困惑的类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50196263/