Ant*_*ina 12 javascript unit-testing jestjs react-native enzyme
我能够模拟警报以测试它的警报方法正在被调用,但我真正想要测试的是按下警报中的确定按钮.
import { Alert } from 'react-native';
it('Mocking Alert', () => {
jest.mock('Alert', () => {
return {
alert: jest.fn()
}
};
});
const spy = jest.spyOn(Alert, 'alert');
const wrapper = shallow(<Search />);
wrapper.findWhere(n => n.props().title == 'Submit').simulate('Press');
expect(spy).toHaveBeenCalled(); //passes
})
Run Code Online (Sandbox Code Playgroud)
我绝对不确定如何测试它.这是我试图测试的通用组件.
export default class Search extends Component{
state = {
someState: false
}
confirmSubmit(){
this.setState(state => ({someState: !state.someState}))
}
onPress = () => {
Alert.alert(
'Confirm',
'Are you sure?'
[{text: 'Ok', onPress: this.confirmSubmit}] //<-- want to test this
)
}
render(){
return(
<View>
<Button title='Submit' onPress={this.onPress}
</View>
)
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人试过这个?
And*_*rle 19
我会模拟模块并导入它以测试间谍.然后触发click事件.这会打电话给间谍.从间谍中你可以得到它mock.calls
用来获取onPress
方法并调用它的params .然后,您可以测试组件的状态.
import Alert from 'Alert'
jest.mock('Alert', () => {
return {
alert: jest.fn()
}
});
it('Mocking Alert', () => {
const wrapper = shallow(<Search />);
wrapper.findWhere(n => n.props().title == 'Submit').simulate('Press');
expect(Alert.alert).toHaveBeenCalled(); // passes
Alert.alert.mock.calls[0][2][0].onPress() // trigger the function within the array
expect(wrapper.state('someState')).toBe(true)
})
Run Code Online (Sandbox Code Playgroud)
Kir*_*rev 11
我在测试警报并尝试模拟警报的 onPress 时遇到了同样的问题。我正在使用 TypeScript 实现我的代码。我设法通过使用间谍来处理这个问题,例如:
const spyAlert = jest.spyOn(Alert, 'alert');
Run Code Online (Sandbox Code Playgroud)
然后要使用 onPress,您需要忽略该行的类型检查,否则您会得到 - Cannot invoke an object which might be 'undefined'。
// @ts-ignore
spyAlert.mock.calls[0][2][0].onPress();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3980 次 |
最近记录: |