开玩笑-模拟ES6类对我不起作用

时间:2020-06-01 20:39:31

标签: javascript unit-testing mocking jestjs

我几乎详细地关注文档(对文件和目录结构进行了一些简单的更改)。使用Jest提供的示例在“ Es6 Class Mocks”中进行“手动模拟”,我具有以下文件结构:

MyProjectExampleDirectory
│   sound-player-consumer.js
│
├───libs
│       sound-player.js
│
├───__mocks__
│       sound-player.js
│
└───__tests__
        sound-player-consumer.test.js

我要测试的脚本如下:

// sound-player-consumer.js
import SoundPlayer from './libs/sound-player';

export default class SoundPlayerConsumer {
  constructor() {
    this.soundPlayer = new SoundPlayer();
  }

  playSomethingCool() {
    const coolSoundFileName = 'song.mp3';
    this.soundPlayer.playSoundFile(coolSoundFileName);
  }
}

我在模仿以下方式:

// __mocks__/sound-player.js
export const mockPlaySoundFile = jest.fn();

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

export default mock;

我的测试如下:

// __tests__/sound-player-consumer.test.js
import SoundPlayer, { mockPlaySoundFile } from '../libs/sound-player';
import SoundPlayerConsumer from './../sound-player-consumer';

jest.mock('../libs/sound-player');

beforeEach(() => {
  // Clear all instances and calls to constructor and all methods:
  SoundPlayer.mockClear();
  mockPlaySoundFile.mockClear();
});

it('We can check if the consumer called the class constructor', () => {
  const soundPlayerConsumer = new SoundPlayerConsumer();
  expect(SoundPlayer).toHaveBeenCalledTimes(1);
});

我收到以下错误消息:

enter image description here

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题,但是我无法在 __ mocks __ 目录中使用它:

const mockPlaySoundFile = jest.fn();
jest.mock('../libs/sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return { playSoundFile: mockPlaySoundFile };
  });
});

以上代码必须在导入之后放置在任何其他代码结构之前

相关问题