我有一个通过以下方式使用react-native-sound
的模块:
const Sound = require('react-native-sound');
...
const something = Sound.DOCUMENT;
const someOtherThing = new Sound();
如何模拟这样的模块?
答案 0 :(得分: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.setCategory
),以及如何添加类实例上的方法(play
,getDuration
等)。 / p>
使用mockFunctions
导出可能会增加一点复杂性。我通过将其分别导入到测试文件(如
import { mockFunctions } from 'react-native-sound';
// ...
expect(mockFunctions.play).toHaveBeenCalled();