【问题标题】:Jest - Mocking ES6 classes doesn't work for me开玩笑 - 模拟 ES6 类对我不起作用
【发布时间】:2020-06-01 20:39:31
【问题描述】:

我几乎详细地关注了文档(有一些简单的文件和目录结构更改)。使用 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);
});

我收到以下错误:

我做错了什么?

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    我已经设法解决了这个问题,但是我无法让它在 __mocks__ 目录中工作:

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

    上面的代码必须放在任何其他代码结构之前,在导入之后

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2018-04-29
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2021-07-03
      • 2021-01-10
      • 2016-11-11
      • 2021-01-05
      相关资源
      最近更新 更多