【问题标题】:Use jest.mock and TypeScript without cluttered type casting?在没有杂乱的类型转换的情况下使用 jest.mock 和 TypeScript?
【发布时间】:2018-10-16 04:49:09
【问题描述】:

当我使用 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 插件可以执行模块扩充吗?

【问题讨论】:

标签: unit-testing typescript jestjs typescript2.0


【解决方案1】:

简单的解决方案是直接从模拟文件中导入。它看起来不优雅,但很有效。

import { readFile } from '../__mocks__/fs';

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 谢谢赫尔曼。我发现强制转换是最冗长的工作方式,因为每次使用它时都需要强制转换。
    猜你喜欢
    • 2014-04-05
    • 2018-10-01
    • 1970-01-01
    • 2023-03-03
    • 2019-03-21
    • 2017-11-05
    • 2016-05-15
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多