使用 jest.mock 和 TypeScript 没有杂乱的类型转换?

Sea*_*ean 7 unit-testing typescript jestjs typescript2.0

当我使用 TypeScript 编译器编译测试并使用 Jest 模拟时,我经常收到以下错误tsc

error TS2339: Property 'mockImplementationOnce' does not exist on type
              'typeof readFile'.
Run Code Online (Sandbox Code Playgroud)

从这个最小的测试:

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...
});
Run Code Online (Sandbox Code Playgroud)


除了:

当模块需要时,TypeScript 插件可以执行模块扩充jest.mock吗?

Her*_*kov 9

最简单的解决方案是像这样导入 fs: const fs = require('fs'),并使用(fs.readFile as jest.Mock).mockImplementationOnce ...