Hello everyone,
I was writing a test to simulate a login and then test if the user was redirect correctly,
const history = createMemoryHistory();
let container, asFragment, getByText;
beforeEach(() => {
history.push("/sign-in");
let res = render(
<Router history={history}>
<Content history={history}></Content>
</Router>
);
container = res.container;
getByText = res.getByText;
asFragment = res.asFragment;
});
jest.mock("../services/user", () => {
return {
login: jest.fn(() => Promise.resolve(true)),
};
});
test("Should redirect to the main page when the login is successful", async () => {
let emailValue = "[email protected]";
const email = container.querySelector('[id="email"]');
const password = container.querySelector('[id="password"]');
fireEvent.change(email, { target: { value: emailValue } });
fireEvent.change(password, { target: { value: "123" } });
expect(email.value).toBe(emailValue);
expect(password.value).toBe("123");
const button = container.querySelector('[type="submit"]');
fireEvent.click(button);
setTimeout(() => {
expect(history.location.pathname).toBe("/");
}, 100);
});
The test worked well but as I'm using route I cant mock a prop to the inside components, so they're rendering after the btn click and generating the An update to SignInForm inside a test was not wrapped in act at the console
Could you guys help me?
Hi @brognilucas, IMO this test is more of an E2E test since you're trying to see the specific journey the user passes within the browser. This should be tested using Cypress (or any other E2E test you'd like).
But that's only my opinion, I'd love to hear other thoughts :)
Have you tried using waitFor instead of setTimeout? setTimeout would fail if the update took longer than 100 milliseconds anyway, though I believe waitFor may also fix your act issue.
Hi guys, thanks for helping me.
The problem was that when I encapsulated the fireEvent inside the act and it works.
Regarding this topic we suggest you to install @testing-library/user-event
This library has a lot of functions that simulate user actions on the browser. Every function is already wrapped with act so you don鈥檛 need to do nothing else. Enjoy the library if you decide to start using it 馃コ
Most helpful comment
Have you tried using
waitForinstead ofsetTimeout?setTimeoutwould fail if the update took longer than 100 milliseconds anyway, though I believewaitFormay also fix youractissue.