I have a basic login form made using Formik, just trying to write an RTL and jest code to fill out the details, submit the form, and navigate to the Home page. Therefore, wrote the following:
it('Fill the form and login', async () => {
render(<Login />)
await userEvent.type(screen.getByTestId('emailInput'), 'neeraj@gmail.com')
await userEvent.type(screen.getByTestId('passwordInput'), 'neeraj')
await userEvent.click(screen.getByTestId('submitBtn'))
expect(window.location.pathname).toBe('/')
})
The above test is getting passed but getting the classic act error.
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
So, referred to this blog post and used waitForElementToBeRemoved function as suggested but now the test is getting failed with a timeout error.
Updated test case with waitForElementToBeRemoved
it('Fill the form and login', async () => {
render(<Login />)
await userEvent.type(screen.getByTestId('emailInput'), 'neeraj@gmail.com')
await userEvent.type(screen.getByTestId('passwordInput'), 'neeraj')
await userEvent.click(screen.getByTestId('submitBtn'))
expect(window.location.pathname).toBe('/')
await waitForElementToBeRemoved(screen.getByTestId('emailInput'))
})
Error:
Timed out in waitForElementToBeRemoved.
Ignored nodes: comments, <script />, <style />
<html>
<head />
<body>
<div>
<div>
<div
data-testid="loginCard"
>
<form
data-testid="loginForm"
>
<div>
<label
for="email-input"
>
Email
</label>
<input
data-testid="emailInput"
id="email-input"
name="email"
type="email"
value="neeraj@gmail.com"
/>
</div>
<div>
<label
for="pass-input"
>
Password
</label>
<input
data-testid="passwordInput"
id="pass-input"
name="password"
type="password"
value="neeraj"
/>
</div>
<button
data-testid="submitBtn"
type="submit"
>
Submit
</button>
</form>
</div>
</div>
</div>
</body>
</html>
19 |
20 | expect(window.location.pathname).toBe('/')
> 21 | await waitForElementToBeRemoved(screen.getByTestId('emailInput'))
| ^
22 | })
23 | })
24 |
at waitForElementToBeRemoved (node_modules/@testing-library/dom/dist/wait-for-element-to-be-removed.js:22:24)
at Object.<anonymous> (tests/login.test.js:21:11)
Tried to wrap those three userEvent s in act function but getting the same timeout error, couldn't figure out where I am going wrong.