jestjs - 无法运行 Jest 提供的 ESM 示例
问题描述
我只是想让Jest 提供的ES6 Class Mocks示例运行绿色。
这是我的代码仓库
我花了很长时间才达到这一点,但测试仍然失败
TypeError: SoundPlayer.mockClear is not a function
被测系统
import SoundPlayer from './sound-player';
export default class SoundPlayerConsumer {
constructor() {
this.soundPlayer = new SoundPlayer();
}
playSomethingCool() {
const coolSoundFileName = 'song.mp3';
this.soundPlayer.playSoundFile(coolSoundFileName);
}
}
考试
import {jest} from '@jest/globals';
import SoundPlayer from './sound-player';
import SoundPlayerConsumer from './sound-player-consumer';
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);
});
被测系统依赖
export default class SoundPlayer {
constructor() {
this.foo = 'bar';
}
playSoundFile(fileName) {
console.log('Playing sound file ' + fileName);
}
}
解决方案
推荐阅读
- sql - SQLYog Pass 使用 WHERE In 子句存储多个逗号分隔值
- python - Python将excel公式向下拖动到范围
- vba - 尝试在 Access 2010 中同步组合框产生对话框
- python - 根据不同数据框中存在的值向熊猫数据框添加一列
- javascript - 模拟 Lodash 方法以返回特定值
- java - Tomcat9 org.apache.tomcat.jdbc.pool.ConnectionPool.init 忽略自定义数据源
- basic-authentication - OpenApi Basic Auth 注解
- mysql - 在 MySQL 中使用子查询时检查插入表的重复条目
- python - 使用 VS Code 运行 Python - 基础知识
- linux - 如何在 ls 输出中按照从左到右的顺序更改文件名?