Проверка логики модульного тестирования, которая выполняется внутри Promise.resolve

#reactjs #jestjs #react-native-android #enzyme

#reactjs #jestjs #реагировать — родной #фермент

Вопрос:

Настройка

  • реакция: 16.6.0
  • react-native: 0.57.4
  • jest : 23.6.0
  • энзим: 3.5.0

У меня есть следующая логика внутри компонента

 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 при getCustomerAccounts().then() запуске

Предложения?

Ответ №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 переменной, чтобы вы могли использовать ее для проверки состояния.