我正在与Jest学习测试本机反应。我有一个页脚组件,该组件使用React Native Tts在单击按钮时播放声音。
https://github.com/ak1394/react-native-tts
当我在设备上运行该代码时,它运行良好,但运行测试时出现以下错误
TypeError: _reactNativeTts.default.addEventListener is not a function
这是我的组件代码。
export default class Footer extends React.Component {
state = {
isPlaying: false
};
_onPress = () => {
Tts.stop()
this.setState({
isPlaying: false
})
this.props.onPressItem();
};
componentDidMount() {
Tts.getInitStatus().then(() => {
console.log('I AM READY TO PLAY SOUND')
Tts.addEventListener('tts-start', (event) => {
console.log("finish", event)
this.setState({
isPlaying: true
})
});
Tts.addEventListener('tts-finish', (event) => {
console.log("finish", event)
this.setState({
isPlaying: false
})
});
Tts.addEventListener('tts-cancel', (event) => {
console.log("finish", event)
this.setState({
isPlaying: false
})
});
Tts.setDefaultLanguage('en-NZ');
Tts.setDefaultRate(0.47);
Tts.setDefaultPitch(0.55);
if(Platform.OS === 'ios')
{
Tts.setDefaultVoice('com.apple.ttsbundle.Samantha-compact');
}
});
}
stopPlayback = () => {
var playBack = this.state.isPlaying
if (playBack === true) {
Tts.stop();
this.setState({
isPlaying: false
})
}
else {
this.setState({
isPlaying: true
})
Tts.speak(this.props.infoText);
}
}
componentWillUnmount() {
Tts.stop()
this.setState({
isPlaying: false
})
}
render() {
return (
<View style={this.props.showKeyboard ? styles.bottomButtonWithKeyboard : styles.bottomButton}>
<TouchableHighlight onPress={this.stopPlayback} underlayColor='#00000000' testID="SoundBtnID">
<Image style={styles.soundStyle} source={this.state.isPlaying ? Images.speaker: Images.muteBtn} />
</TouchableHighlight>
<TouchableHighlight style={styles.buttonNextStyle} onPress={this._onPress} underlayColor='#00000000' testID="NextBtnID">
<Text style={styles.buttonText}>NEXT</Text>
</TouchableHighlight>
</View>
)
}
}
下面是FooterTest.js的代码
import 'react-native'
import React from 'react'
import Footer from '../../App/Components/FooterButton/Footer'
import renderer from 'react-test-renderer'
test('Footer test', () => {
let i = 0
const onPress = () => i++
const tree = renderer.create(<Footer infoText='This is a test' onPressItem={() => {}} />).toJSON()
expect(tree).toMatchSnapshot()
})
如果我注释掉componentDidMount
,测试也会通过。不知道我在做什么错。查看了Tts的文档。任何帮助将不胜感激。预先感谢