模拟所需的类而不在Jest测试中实际导入它

哈立德

使用Jest示例,所需的类

// sound-player.js
export default class SoundPlayer {
  constructor() {    
    // do something
  }
}

和正在测试的课程:

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

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

我想测试,如果SoundPlayerConsumer曾经被称为(创建的对象)SoundPlayerplaySomethingCool()我的理解是,它看起来像这样:

import SoundPlayer from './sound-player';
import SoundPlayerConsumer from './sound-player-consumer';
jest.mock('./sound-player');

beforeEach(() => {
  SoundPlayer.mockClear();
});

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

但是,在我的情况下,我不想导入,./sound-player因为它具有许多要求和依赖关系,这对我的测试来说是一个过高的选择,因此,我只想手动模拟该类。这是我到目前为止尝试过的:

  import SoundPlayerConsumer from './sound-player-consumer'; 
  const SoundPlayer = jest.mock('./sound-player', () => {
    return function() {
      return {}
    }
  });
  it('check if the consumer is called', () => {
    const soundPlayerConsumer = new SoundPlayerConsumer();
    soundPlayerConsumer.playSomethingCool();
    expect(SoundPlayer).toHaveBeenCalledTimes(1);
  });

但这是我得到的结果,我Matcher error: received value must be a mock or spy function尝试了其他几种变体,但最终总是得到相同的结果。

我已经读过Jest Manual Mocks,但无法完全掌握。

哈立德

根据Jest docsmockImplementation可用于模拟类构造函数。因此,您可以模拟一个类并使用来返回jest函数mockImplementation

  import SoundPlayerConsumer from './sound-player-consumer';

  // must have a 'mock' prefix
  const mockSoundPlayer = jest.fn().mockImplementation(() => {
    return {}
  });

  const SoundPlayer = jest.mock('./sound-player', () => {
    return mockSoundPlayer
  });

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Mockito-测试中类(CUT)中未使用所需的返回的模拟对象

在Jest中模拟类常量

Angest Jest或Jasmine测试:如何正确监视/模拟从经过测试的类中调用的静态对象?

在 Python 中模拟导入的类

Jest中的模拟测试与模拟测试之间的区别

Typescript,在Redux操作中测试Api调用,在Enzyme,Jest中模拟类

模拟单元测试用例所需的类更改

测试类中的模拟接口

被测试的类正在调用实际对象,而不是模拟对象

OCMock可以模拟一个类,使其在被测试的代码中自动使用模拟的实例而不注入它吗

在 Typescript Jest 中模拟导出的类

用Jest在javascript中模拟类原型

有没有办法在 Jest 的同一个测试文件中测试模拟函数和实际函数?

模拟使用Typescript和Jest进行测试的类

如何用Jest覆盖(或模拟)类方法以测试功能?

在指令测试中模拟所需的控制器

Python 模拟未导入的类中的方法

Laravel 5.1中的(实际)单元测试模拟请求

在junit测试中模拟DateFormat类

使用Jest模拟导入模块中的外部用户模块

如何使用Jest在TypeScript中模拟导入的函数?

是否可以从模拟模块本身中要求模拟 Jest 模块的原始/实际实现?

使用Jest模拟命名的导入

从导入中模拟导入

如何在Jest测试函数中模拟变量?

如何重置Jest中测试之间的模拟调用记录?

React Native:在Jest单元测试中模拟离线设备

如何在React Jest测试中“模拟” navigator.geolocation

如何在Jest测试中模拟StatusBarManager.getHeight?