我正在使用与apollo客户端的反应,我正在尝试测试一个函数,它需要一个graphQL变异。由于这是该功能的单元测试,我不想测试突变。所以我需要模仿突变。这是我的功能:
changeContent (event) {
const { content } = this.state
const { id, language, changeMutation, t } = this.props
changeMutation({
variables: {
id,
content
},
refetchQueries: [{
query: getContent,
variables: {
id,
language
}
}]
}).then(response => {
this.setState({ content: response.data.changeContent.content })
}).catch(error => {
this.setState({ content })
console.error(error)
toast.error(t('error:content'))
})
}
这就是我开始测试它的方式:
it('changeContent() should call mutation', () => {
// SETUP
const initial = 'Initial value'
const new = 'New value'
wrapper = shallow(<Content
id='123'
language='en'
t={jest.fn()}
changeMutation={jest.fn()}
/>)
wrapper.setState({ content: initial })
// EXECUTE
wrapper.instance().changeContent()
// VERIFY
expect(wrapper.instance().state.content).toEqual(new)
})
但我不明白如何处理then
和catch
。
我认为你有两个可能的期望:
所以你可以测试你的预期行为,为每个期望做两个测试,并且在每个测试中正确地模拟changeMutation可能是这样的:
当承诺得到解决时:
it('changeContent() should call mutation', async () => {
// SETUP
const initial = 'Initial value'
const new = 'New value'
wrapper = shallow(<Content
id='123'
language='en'
t={jest.fn()}
changeMutation={jest.fn(()=>Promose.resolve(yourExpectedResponse)}
/>)
wrapper.setState({ content: initial })
// EXECUTE
await wrapper.instance().changeContent()
// VERIFY
expect(wrapper.instance().state.content).toEqual(new)
})
当来自changeMutation的承诺被拒绝时。
it('changeContent() should call mutation', async () => {
// SETUP
const initial = 'Initial value'
const new = 'New value'
wrapper = shallow(<Content
id='123'
language='en'
t={jest.fn()}
changeMutation={jest.fn(()=>Promose.reject(yourExpectedError´)}
/>)
wrapper.setState({ content: initial })
// EXECUTE
await wrapper.instance().changeContent()
// VERIFY
expect(wrapper.instance().state.content).toEqual(initial)
})
如果这是你要求的,请告诉我