为什么获取一个函数的状态有效而从另一个函数获取状态无效?



我正在测试不同函数的状态,一个为真,另一个为假,一个通过,另一个失败。我不知道为什么会这样。

//default
this.state = { passwordChangeOpen: false }
openPasswordChange () {
this.setState({ passwordChangeOpen: true })
}
onClosePasswordChange () {
this.setState({ passwordChangeOpen: false })
}

测试

test('should', () => {
const wrapper = mount(<SettingsItemPassword {...mockPropsForComponent} />)
const instance = wrapper.instance()
instance.openPasswordChange()
expect(wrapper.state('passwordChangeOpen')).toBeTruthy()
})
test('should2', () => {
const wrapper = mount(<SettingsItemPassword {...mockPropsForComponent} />)
const instance = wrapper.instance()
instance.onClosePasswordChange()
expect(wrapper.state('passwordChangeOpen')).toBeFalsy()
})

第一个测试失败并显示错误

不变违规:在上下文或道具中都找不到"存储"......

但第二次测试通过了。 有什么建议吗?

好的,请记住,设置状态是async.由于将默认值设置为 false,因此第二个断言将传递。

试着想出这样的东西

test('should', done => {
const wrapper = mount(<SettingsItemPassword {...mockPropsForComponent} />)
const instance = wrapper.instance()
instance.openPasswordChange()
setTimeout(() => {
wrapper.update()
expect(wrapper.state('passwordChangeOpen')).toBeTruthy()
done()
})
})

最新更新