我使用手动模拟(在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
等)使用原型添加。
有一点增加的复杂性,您可能不需要使用
mockFunctions
出口。我使用它来检查对模拟函数的调用,方法是将其单独导入测试文件,如下所示
import { mockFunctions } from 'react-native-sound';
// ...
expect(mockFunctions.play).toHaveBeenCalled();