angular - 带有 Jest 的 Angular 8 - 'jasmine' 没有导出的成员 'SpyObj'
问题描述
我有一个具有默认 Karma 测试运行器的 Angular CLI 项目。我使用本教程将 Karma 替换为 Jest,并注意到一些测试通过了一些失败。
例如,在测试级别声明一个变量:
let mockObj: jasmine.SpyObj<MyClass>;
抛出错误:
error `"Namespace 'jasmine' has no exported member 'SpyObj'`
@angular-builders/jest: "^8.3.2"
jest: "^24.9.0"
jasmine-core: "3.5.0"
@types/jest: "^24.9.0"
@types/jasmine: "3.5.0"
@types/jasminewd2": "2.0.8"
解决方案
当您选择 Jest 时,您必须使用 Jest 间谍和模拟而不是 Jasmine 间谍。或其他一些测试双库,如Sinon。
Jest类模拟示例
import SoundPlayer from './sound-player';
const mockPlaySoundFile = jest.fn();
jest.mock('./sound-player', () => {
return jest.fn().mockImplementation(() => {
return {playSoundFile: mockPlaySoundFile};
});
});
beforeEach(() => {
SoundPlayer.mockClear();
mockPlaySoundFile.mockClear();
});
it('The consumer should be able to call new() on SoundPlayer', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
// Ensure constructor created the object:
expect(soundPlayerConsumer).toBeTruthy();
});
it('We can check if the consumer called the class constructor', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
expect(SoundPlayer).toHaveBeenCalledTimes(1);
});
it('We can check if the consumer called a method on the class instance', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
const coolSoundFileName = 'song.mp3';
soundPlayerConsumer.playSomethingCool();
expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);
});
推荐阅读
- c# - 您可以使用字符串变量来确定要调用哪个函数吗?还是有更好的方法来编辑类中的变量?
- java - Response.entity().build 不返回所有结果
- javascript - 如何将 jquery 类型导入打字稿
- java - 不明确的列名:使用 Room Presistent Library 在 AndroidStudio 中输入
- ios - URLSessionTask 实例变量与局部变量 - 谁拥有引用?
- raspberry-pi3 - 树莓派的 Windows iot LCD 屏幕
- c - 添加额外的“int”关键字时,while循环不会中断吗?
- excel - 将 Excel 工作表导出为 PDF - 如何修改字体、间距、大小?
- php - 关于脱脂框架的许可
- jquery - 如何在跨度元素 wpcf7-form-control-wrap 内放置标签