Fac*_*cca 5 unit-testing mocking reactjs jestjs react-native
当我尝试使用 Jest模拟react-native-sound 时,出现以下错误:
//PlayerService.js
import Sound from 'react-native-sound';
try {
console.log('Sound: ' + JSON.stringify(Sound)); //Sound: {}
_trackPlaying = new Sound('path', Sound.LIBRARY, error => { });
} catch (error) {
console.log('error: ' + JSON.stringify(error)); //error: {}
}
Run Code Online (Sandbox Code Playgroud)
//PlayerService.tests.js
jest.mock('react-native-sound', () => ({
Sound: jest.fn((path, type, callback) => {
})
}));
Run Code Online (Sandbox Code Playgroud)
// 包.json
{
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-jest": "^21.2.0",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-flow": "^6.23.0",
"flow": "^0.2.3",
"jest": "^21.2.1"
},
"jest": {
"modulePathIgnorePatterns": [
"__mocks__/"
]
},
"dependencies": {
"react-native-sound": "^0.10.4"
}
}
Run Code Online (Sandbox Code Playgroud)
或者,我尝试在一个单独的文件(__mock__文件夹)中设置一个手动模拟,运气类似:
{
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-jest": "^21.2.0",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-flow": "^6.23.0",
"flow": "^0.2.3",
"jest": "^21.2.1"
},
"jest": {
"modulePathIgnorePatterns": [
"__mocks__/"
]
},
"dependencies": {
"react-native-sound": "^0.10.4"
}
}
Run Code Online (Sandbox Code Playgroud)
任何指导或建议将不胜感激。非常感谢!
嗯,最后我发现了问题。
我尝试进行模拟的方式是问题所在,所以我所做的是返回一个新函数来模拟我需要模拟的内容:
jest.mock('react-native-sound', () => {
var _filename = null;
var _basePath = null;
var SoundMocked = (filename, basePath, onError, options) => {
_filename = filename;
_basePath = basePath;
onError();
}
SoundMocked.prototype.filename = () => _filename;
SoundMocked.prototype.basePath = () => _basePath;
SoundMocked.prototype.play = function (onEnd) { };
SoundMocked.prototype.pause = function (callback) { };
SoundMocked.prototype.stop = function (callback) { };
SoundMocked.prototype.reset = function () { };
SoundMocked.prototype.release = function () { };
SoundMocked.prototype.getDuration = function () { };
SoundMocked.LIBRARY = 2;
return SoundMocked;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |