相关疑难解决方法(0)

使用 Typescript 从 Jest 手动模拟导入函数

我正在 Typescript 项目中使用 Jest 创建一个自定义模拟(ES6 类)。模拟创建了一些最终导出,mock.fn()以便它们可以在测试套件中被监视。

一个例子可能是 Jest 文档中的官方文档 ( https://jestjs.io/docs/en/es6-class-mocks#manual-mock )。在那里,这个SoundPlayer类被嘲笑了,因为它是它唯一的方法playSoundFile。该方法是使用 a 模拟的jest.fn(),它被导出以用于测试。

// soundPlayer.ts
export default class SoundPlayer {
  foo: string = 'bar';

  playSoundFile(filename: string) {
    console.log(`Playing sound file ${filename}`);
  }
}
Run Code Online (Sandbox Code Playgroud)
// __mocks__/soundPlayer.ts
export const mockPlaySoundFile = jest.fn();

const mock = jest.fn().mockImplementation(() => {
  return { playSoundFile: mockPlaySoundFile };
});

export default mock;
Run Code Online (Sandbox Code Playgroud)
// __tests__/soundPlayer.ts
import SoundPlayer, { mockPlaySoundFile } from '../soundPlayer';

jest.mock('../soundPlayer');

beforeEach(() => {
  mockPlaySoundFile.mockClear();
});

it('is …
Run Code Online (Sandbox Code Playgroud)

mocking typescript jestjs

5
推荐指数
2
解决办法
1655
查看次数

标签 统计

jestjs ×1

mocking ×1

typescript ×1