Cos*_*rix 5 mocking typescript jestjs
我正在 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 called with filename', () => {
const filename = 'song.mp3';
const soundPlayer = new SoundPlayer();
soundPlayer.playSoundFile(filename);
expect(mockPlaySoundFile).toBeCalledWith(filename);
});
Run Code Online (Sandbox Code Playgroud)
测试按预期工作,但 TS 在尝试导入模拟mockPlaySoundFile函数时会通知错误(这对我来说很有意义)。那是因为,显然,mockPlaySoundFile不存在于soundPlayer.ts. 但是由于jest.mock('../soundPlayer');模拟是在引擎盖下导入的,因此导出确实存在。
有没有办法通知 TS 在这种情况下查看模拟?
2022 年 9 月 29 日更新:
该mocked功能已集成到 jest 中,并且在 ts-jest 中不再可用。
原答案:
解决此问题的最简单方法是使用ts-jest的mocked()助手。助手将确保您可以访问模拟测试方法。__tests__/soundPlayer.ts那么将如下所示:
// __tests__/soundPlayer.ts
import { mocked } from "ts-jest/utils";
import SoundPlayer from '../soundPlayer';
jest.mock('../soundPlayer');
const soundPlayer = mocked(new SoundPlayer());
beforeEach(() => {
soundPlayer.playSoundFile.mockClear();
});
it('is called with filename', () => {
const filename = 'song.mp3';
soundPlayer.playSoundFile(filename);
expect(soundPlayer.playSoundFile).toBeCalledWith(filename);
});
Run Code Online (Sandbox Code Playgroud)
如果你确实想包含,mockPlaySoundFile可以通过告诉 Typescript 编译器抑制导入错误来实现:
// @ts-ignore
import { mockPlaySoundFile } from '../soundPlayer';
Run Code Online (Sandbox Code Playgroud)
另外,请查看我的存储库中的示例: https: //github.com/tbinna/ts-jest-mock-examples,特别是您的soundPlayer示例: https: //github.com/tbinna/ts-jest -mock-examples/tree/master/sound-player
我有同样的问题,我只有一个解决方法。我的问题是我从节点手动模拟 fs。
所以我有一个“fs”的手动模拟,大致如下:
const fs = jest.genMockFromModule("fs");
let mockFiles = {};
function __clearMocks(){
mockFiles = {};
}
module.exports = fs;
Run Code Online (Sandbox Code Playgroud)
很明显,当我的测试用例导入 fs 时,它不起作用:
import * as fs from 'fs';
fs.__clearMocks();
Run Code Online (Sandbox Code Playgroud)
为了使其正常工作,我创建了该类型的扩展:
declare module 'fs' {
export function __clearMocks(): void;
}
Run Code Online (Sandbox Code Playgroud)
所以现在我可以这样修改我的测试用例:
import * as fs from 'fs';
import 'fsExtension';
fs.__clearMocks();
Run Code Online (Sandbox Code Playgroud)
希望这对您有帮助!
| 归档时间: |
|
| 查看次数: |
1655 次 |
| 最近记录: |