【问题标题】:How to mock a module exporting a class with class variables using jest如何使用 jest 模拟导出具有类变量的类的模块
【发布时间】:2018-12-04 06:06:47
【问题描述】:

我有一个模块以下列方式使用react-native-sound

const Sound = require('react-native-sound');
...
const something = Sound.DOCUMENT;
const someOtherThing = new Sound();

如何模拟这样的模块?

【问题讨论】:

  • 为了测试?你为什么嘲笑它?
  • 是的,我想测试一个使用这个模块的组件。
  • 你的测试框架是什么?开玩笑?

标签: javascript react-native jestjs


【解决方案1】:

我使用手动模拟(在 __mocks__ 文件夹中)模拟了 react-native-sound,如下所示:

const isFakeFilename = filename => /^blah.*/.test(filename);

const mockFunctions = {
  play: jest.fn(cb => {
    console.log('*** Playing sound! ***');
    cb && cb(isFakeFilename(this.filename) ? false : true);
  }),
  setCategory: jest.fn(),
  getDuration: jest.fn(() => 100),
  getNumberOfChannels: jest.fn(() => 8)
};

const Sound = function(filename, blah2, cb) {
  this.play = mockFunctions.play.bind(this);
  this.filename = filename;
  const savedFilename = filename;
  setTimeout(() => {
    if (isFakeFilename(savedFilename)) {
      cb && cb(new Error('File does not exist! (mocked condition)'));
    } else {
      cb && cb();
    }
  });
};

Sound.prototype.play = mockFunctions.play.bind(Sound.prototype);
Sound.prototype.getDuration = mockFunctions.getDuration;
Sound.prototype.getNumberOfChannels = mockFunctions.getNumberOfChannels;

Sound.setCategory = mockFunctions.setCategory;

export default Sound;
export { mockFunctions };

注意如何直接添加 Sound 导入上的方法 (Sound.setCategory),以及使用原型添加类实例上的方法 (playgetDuration 等)。

使用mockFunctions 导出可能不需要额外的复杂性。我使用它来检查对模拟函数的调用,方法是将其单独导入到测试文件中,如

import { mockFunctions } from 'react-native-sound';
// ...
expect(mockFunctions.play).toHaveBeenCalled();

【讨论】:

  • 使用 mock 文件夹不可能每个测试都有不同的模拟内部,对吧?
  • 您可以使用 mockImplementation / mockImplementationOnce 即时更改它。 jestjs.io/docs/en/mock-function-api#mockfnmockimplementationfn。您需要将模拟模块导入您的测试文件来执行此操作;请参阅链接中的示例('SomeClass')。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 2021-04-14
  • 2021-01-21
  • 2020-02-23
  • 2021-06-27
相关资源
最近更新 更多