簡體   English   中英

React 測試庫的 waitFor() 返回 null

[英]React testing library's waitFor() returns null

我正在測試拒絕我的登錄表單的提交事件。 如果用戶只是提交了表單而沒有填寫用戶名和密碼,則必須顯示兩條錯誤消息並且它應該通過測試。 但測試結果卻相反:顯示用戶名和密碼錯誤信息為null 我嘗試使用setTimeout() ,因為由於 axios, onSubmit事件是異步的,但它仍然沒有通過測試。 我將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)
})

測試結果

對測試進行了一些更改,可能會解決此問題。 請在以下代碼中找到它們作為注釋

// 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, findByTestId, queryByTestId } = render(<Index />)

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

    fireEvent.submit(getByTestId('form'))

    // Here we can use waitFor which waits until the promise triggered by the last fireEvent finishes.
    await waitFor(() => {
        expect(getByTestId('submit-button').disabled).toBeFalsy()
    })

    // Finally, you should be able to just use getByTestId 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()
})

如果這些建議不起作用,請同時復制正在測試的組件的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM