unit-testing - 使用 jest.mock 和 TypeScript 而无需困惑的类型转换?

标签 unit-testing typescript jestjs typescript2.0

当我使用 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...
});


除了:

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/

相关文章:

unit-testing - 单元测试 DbContext

python - 断言不相等的相同数据帧 - Python Pandas

c# - 使用 db 文件进行 sqlite 单元测试

javascript - 如何为使用 Vuex 存储的 Vue 表单组件编写 Jest 单元测试?

react-native - 类型错误 : Cannot read property 'params' of undefined Jest Testing - React Native

node.js - Jest : how to restore to a previous mocked implementation (not the original)

unit-testing - VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook

javascript - Node/JS 在导入时创建新实例

具有来自 Web 服务的动态元数据的 Angular 6 元服务

angular - PrimeNG 日历表单组验证问题