Javascript 如何模拟使用jest导出带有类变量的类的模块

Javascript 如何模拟使用jest导出带有类变量的类的模块,javascript,react-native,jestjs,Javascript,React Native,Jestjs,我有一个模块使用反应本地声音,方法如下: const Sound = require('react-native-sound'); ... const something = Sound.DOCUMENT; const someOtherThing = new Sound(); 如何模拟这样一个模块?我已经使用一个手动模拟(在_mocks__文件夹中)模拟了react本机声音,如下所示: const isFakeFilename = filename => /^blah.*/.test(

我有一个模块使用
反应本地声音
,方法如下:

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

如何模拟这样一个模块?

我已经使用一个手动模拟(在_mocks__文件夹中)模拟了react本机声音,如下所示:

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.setCategory
),以及如何使用原型添加类实例上的方法(
play
getDuration
等)

使用
mockFunctions
export可能不需要增加一些复杂性。我使用它来检查对模拟函数的调用,方法是将其单独导入测试文件,如

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

用于测试?你为什么要模仿它?是的,我想测试一个使用这个模块的组件。你的测试框架是什么?Jest?使用mock文件夹,每个测试不可能有不同的模拟内部构件,对吗?您可以使用
mockImplementation
/
mockImplementationOnce
动态更改它。为此,您需要将模拟模块导入到测试文件中;请参见链接中的示例(“SomeClass”)。