验证在Promise.resolve中运行的单元测试逻辑

时间:2019-04-12 02:17:11

标签: reactjs jestjs react-native-android enzyme

设置

  • 反应:16.6.0
  • 本机:0.57.4
  • 笑话:23.6.0
  • 酶:3.5.0

我在组件内部具有以下逻辑

  <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

建议?

1 个答案:

答案 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分配给变量,以便您可以使用它来检查状态。