设置
我在组件内部具有以下逻辑
<ListView items="{{ storeList }}" row="1" itemTap="{{showDetail}}">
我要测试的是像这样使用onRefresh = () => {
const { getCustomerAccounts } = this.props
this.setState({ refreshing: true })
getCustomerAccounts()
.then(() => this.setState({ refreshing: false }))
};
jest
测试运行正常,但是我无法测试 describe('Instance', () => {
const getCustomerAccountsMock = jest.fn(() => Promise.resolve({}))
const props = {
getCustomerAccounts: getCustomerAccountsMock,
}
const instance = shallow(<Component {...props} />).instance()
describe('onRefresh', () => {
it('should call getCustomerAccounts', () => {
instance.onRefresh()
expect(getCustomerAccountsMock).toHaveBeenCalled()
expect(getCustomerAccountsMock).toHaveBeenCalledTimes(1)
expect(getCustomerAccountsMock.mock.calls[0][0]).toBeUndefined()
})
})
})
运行时会发生什么情况
基本上我想测试getCustomerAccounts().then()
运行时this.state.refreshing
是否设置为false
建议?
答案 0 :(得分:1)
从Promise
返回onRefresh
:
onRefresh = () => {
const { getCustomerAccounts } = this.props
this.setState({ refreshing: true })
return getCustomerAccounts() // <= return the Promise
.then(() => this.setState({ refreshing: false }))
};
...然后您可以像这样测试它:
describe('Instance', () => {
const getCustomerAccountsMock = jest.fn(() => Promise.resolve({}))
const props = {
getCustomerAccounts: getCustomerAccountsMock,
}
const wrapper = shallow(<Component {...props} />)
const instance = wrapper.instance()
describe('onRefresh', () => {
it('should call getCustomerAccounts', async () => { // <= async test function
await instance.onRefresh() // <= await the Promise
expect(getCustomerAccountsMock).toHaveBeenCalled()
expect(getCustomerAccountsMock).toHaveBeenCalledTimes(1)
expect(getCustomerAccountsMock.mock.calls[0][0]).toBeUndefined()
expect(wrapper.state('refreshing')).toBe(false); // Success!
})
})
})
详细信息
返回Promise
可让您await
在测试中。
使用async
测试函数,以便可以await
返回的Promise
。
将wrapper
分配给变量,以便您可以使用它来检查状态。