如何模拟使用Jest导出具有类变量的类的模块 [英] How to mock a module exporting a class with class variables using jest
问题描述
我有一个通过以下方式使用react-native-sound
的模块:
I have a module using react-native-sound
in the following ways:
const Sound = require('react-native-sound');
...
const something = Sound.DOCUMENT;
const someOtherThing = new Sound();
我该如何模拟这样的模块?
How do I mock such a module?
推荐答案
我使用手动模拟(在__mocks__文件夹中)模拟了react-native-sound:
I've mocked react-native-sound using a manual mock (in the __mocks__ folder) which looks like this:
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
等).
Note how methods on the Sound import are added directly (Sound.setCategory
), and methods on instances of the class (play
, getDuration
etc.) are added using the prototype.
使用mockFunctions
导出可能会增加一点复杂性.我通过将其分别导入到测试文件(如
There's a little added complexity that you may not need using the mockFunctions
export. I use that to check for calls to the mocked functions by importing it separately into the test file like
import { mockFunctions } from 'react-native-sound';
// ...
expect(mockFunctions.play).toHaveBeenCalled();
这篇关于如何模拟使用Jest导出具有类变量的类的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!