Реагирующая библиотека тестирования waitFor () возвращает ноль - PullRequest
0 голосов
/ 07 апреля 2020

Я проверяю отклонение события отправки моей формы входа. Если пользователь только что отправил форму без заполнения имени пользователя и пароля, должны появиться два сообщения об ошибке, и он должен пройти тест. Но результат теста показывает обратное: он показывает, что сообщения об ошибке имени пользователя и пароля null. Я попытался использовать setTimeout(), поскольку событие onSubmit является асинхронным из-за топора ios, но оно все еще не прошло тест. Что-то не так в том, как я использую утилиту waitFor() для события асинхронной отправки?

it('Should render username and password error messages when both inputs are blank', () => {
    const { getByTestId, queryByTestId } = render(<Index />)

    fireEvent.submit(getByTestId('form'))

    expect(getByTestId('submit-button').disabled).toBeTruthy()

    setTimeout(async () => {
        expect(getByTestId('submit-button').disabled).toBeFalsy()

        const usernameError = await waitFor(() => queryByTestId('username-error'))
        expect(usernameError).toBeInTheDocument()

        const passwordError = await waitFor(() => queryByTestId('password-error'))
        expect(passwordError).toBeInTheDocument()
    }, 0)
})

Test result

1 Ответ

0 голосов
/ 07 апреля 2020

В тесте есть несколько изменений, которые могут решить эту проблему. Пожалуйста, найдите их в следующем коде как комментарии

// The first is adding async to the callback of your `it` so you don't have to use a timeout
it('Should render username and password error messages when both inputs are blank', async () => {
    const { getByTestId, queryByTestId } = render(<Index />)

    expect(getByTestId('submit-button').disabled).toBeTruthy()

    // The second thing is to wrap your fireEvent call in an act (exported from react-testing library). By doing this, the test will wait for promises to be resolved
    await act(async () => {
        fireEvent.submit(getByTestId('form'))
    })

    expect(getByTestId('submit-button').disabled).toBeFalsy()

    // Finally, you should be able to just use findyByTestId to locate the elements you need, and given that the promises are resolved, they should be in the document
    expect(getByTestId('username-error')).toBeInTheDocument()
    expect(getByTestId('password-error')).toBeInTheDocument()
})

Пожалуйста, если эти рекомендации не работают, также скопируйте код для тестируемого компонента

...