Writing tests
This is what we want to test in SignupPage.tsx:
The form is filled up correctly.
The values submitted come from the form.
The token is added to the local storage.
The user is redirected to the home page.
To achieve this, we will need to:
Simulate keyboard and mouse events.
Mock Apollo provider.
Mock
localStorage.Mock
history.
Simulate keyboard and mouse events
There are two ways to do this: Simulate from react-dom/test-utils or using dispatchEvent:
import { act, Simulate } from "react-dom/test-utils";
const emailInput = container.querySelector("input[name=emailAddress]")!;
emailInput.setAttribute("value", "[email protected]");
Simulate.change(emailInput);
const submitButton = container.querySelector("button[type=submit]")!;
expect(submitButton.textContent).toEqual("Submit");
submitButton.dispatchEvent(new MouseEvent("click"));Mock Apollo provider
We need to export the mutation from the page to be able to use it in our test:
We can now use MockedProvider from@apollo/react-testing.
Mock local storage
Jest comes with ways to easily mock functions:
The important part is to know how to mock things. (e.g Storage.prototype for localStorage).
Mock history
We can use createMemoryHistory fromhistory.
Bring it together
Last updated
Was this helpful?