gpt4 book ai didi

reactjs - 无法使用 Jest 模拟 react 原生声音

转载 作者:行者123 更新时间:2023-12-03 13:47:39 25 4
gpt4 key购买 nike

当我尝试 mock react-native-sound 时使用 Jest 我收到以下错误:

//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) => {

})
}));

//包.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

任何指导或建议将不胜感激。非常感谢!

最佳答案

嗯,最后我发现了问题。

我尝试进行模拟的方式是问题所在,所以我所做的是返回一个新函数来模拟我需要模拟的内容:

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;
});

关于reactjs - 无法使用 Jest 模拟 react 原生声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com