当我使用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<{}>TypeScript插件可以在jest.mock需要模块时执行模块增强吗?
发布于 2018-05-22 21:08:19
最简单的解决方案是像这样导入fs:const fs = require('fs'),并使用(fs.readFile as jest.Mock).mockImplementationOnce ...
发布于 2018-08-20 11:08:52
简单的解决方案是直接从模拟文件导入。它看上去不雅致,但很管用。
import { readFile } from '../__mocks__/fs';https://stackoverflow.com/questions/50196263
复制相似问题