简体   繁体   English

开玩笑 - Mocking ES6 课程对我不起作用

[英]Jest - Mocking ES6 classes doesn't work for me

I'm following the documentation almost in detail (with some simple file and directory structure changes).我几乎详细地关注了文档(进行了一些简单的文件和目录结构更改)。 Using the example offered by Jest to make 'manual mocks' in 'Es6 Class Mocks', I have the following files structure:使用 Jest 提供的示例在“Es6 Class Mocks”中制作“手动模拟”,我有以下文件结构:

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

My script to test is as follows:我要测试的脚本如下:

// 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);
  }
}

I am mocking the following way:我是mocking,方式如下:

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

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

export default mock;

and my test is the following:我的测试如下:

// __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);
});

I'm getting de following error:我收到以下错误:

在此处输入图像描述

What am I doing wrong?我究竟做错了什么?

I have managed to resolve the issue, however I am unable to get it to work in the __mocks__ directory:我已经设法解决了这个问题,但是我无法让它在__mocks__目录中工作:

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

The code above must be placed before any other code structure, after imports上面的代码必须放在任何其他代码结构之前,在导入之后

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM