首页 > 解决方案 > 无法运行 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);
    }
}

标签: jestjsmockinges6-modules

解决方案


推荐阅读