Cześć, zacząłem się uczyć robić automatyczne testy w oparciu o jest dla reacta. Jednak co chwilę napotykam niezbyt zrozumiałe dla mnie sytuację, jedną z nich jest problem przedstawiony poniżej.
Mam komponent App i w nim komponent LoginPage (LoginPage korzysta z propsów App, stąd te moje wywołanie obu w metodzie render()). Test polega na sprawdzeniu czy po wciśnięciu przycisku strona jest przerenderowana i pojawił się komunikat - proste prawda :D? Brak danych logowania - to błędne dane. Jednak problem tkwi w tym, że nie rozumiem dlaczego waitFor nie zwraca mi obiektu, tylko undefined, pomimo, że na debug() widzę, że obiekt się przerenderował i że istnieje poszukiwany przeze mnie komunikat o błędzie. Próbowałem dwojako: dobrać się do niego za pomocą testId oraz getByText, obie metody zwracają to samo. Troszkę to wygląda dla mnie tak, jakbym pomimo przerenderowania komponentu, w teście sprawdzał poprzedni stan?
import { render, fireEvent, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import App from '../../App'
import LoginPage from './LoginPage'
test('error-login-text', async () => {
const { getByText, getByTestId, debug } = render(
<App>
<LoginPage />
</App>
)
const button = getByTestId('login-button')
fireEvent.click(button)
console.log('_________', 'Przed renderowaniem', '_________')
debug()
const errorText = await waitFor(() => {
getByTestId('login-error')
})
console.log('_________', 'Po wyrenderowaniu', '_________')
debug()
console.log('_________', 'Wynik', '_________',
'\n', errorText)
expect(errorText.children[0]).toEqual('Incorrect login data!')
})
<form>
<input
id="email"
type="text"
placeholder="Enter your email"
onChange={onLogin}
value={props.emailValue}
/>
<input
id="password"
type="password"
placeholder="Enter your password"
onChange={onPassword}
password={props.passwordValue}
/>
<button
data-testid='login-button'
type="submit"
onClick={props.onSubmit}
>
Login
</button>
{props.failedLogin === true ?
<p
data-testid='login-error'
>
Incorrect login data!
</p> : <></>}
</form>
Z góry dzięki.