【发布时间】:2018-05-05 16:53:41
【问题描述】:
当我尝试用 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: {}
}
//PlayerService.tests.js
jest.mock('react-native-sound', () => ({
Sound: jest.fn((path, type, callback) => {
})
}));
// package.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"
}
}
或者,我尝试在一个单独的文件(__mock__ 文件夹)中设置手动模拟,但运气相似:
//__mocks__/react-native-sound.js
const Sound = jest.genMockFromModule('react-native-sound');
Sound = (path, type, callback) => {
console.log("mocked");
}
module.exports = Sound;
//__tests__/PlayerService.tests.js
jest.mock('react-native-sound'); // doesn't work
任何指导或建议将不胜感激。非常感谢!
【问题讨论】:
-
也许你还需要模拟
Sound.LIBRARY? -
在这个例子中没有,但我做到了。我没有做的是模拟正在导出的任何内容。我要试试。
-
您遇到的错误是什么?我似乎在你的问题中找不到它。
-
错误显示为注释:
//error: {}。但我终于弄清楚了错误是什么。
标签: reactjs unit-testing react-native mocking jestjs