Some useful query for select element in form
- Query input with name:
screen.getByRole("textbox", { name: /email/i })
- Submit form via button:
fireEvent.submit(screen.getByRole("button"))
-
Add text value into input:
// Get by role => need aria-label="email" (same as name attribute) to use this query by name fireEvent.input(screen.getByRole("textbox", { name: /email/i }), { target: { value: "value inputted" }, }); // Get by label fireEvent.input(screen.getByLabelText("password"), { target: { value: "password" }, });
Mock some common library
-
Next Router
jest.mock("next/router", () => ({ useRouter() { return { route: "/", pathname: "", query: "", asPath: "", push: jest.fn(), events: { on: jest.fn(), off: jest.fn(), }, beforePopState: jest.fn(() => null), prefetch: jest.fn(() => null), }; }, })); const useRouter = jest.spyOn(require("next/router"), "useRouter"); // Then in the tests useRouter.mockImplementation(() => ({ route: "/", pathname: "", query: "", asPath: "", push: jest.fn(), events: { on: jest.fn(), off: jest.fn(), }, beforePopState: jest.fn(() => null), prefetch: jest.fn(() => null), }));
Setup mock global:
- Create a file mock in the folder:
/jest/**mocks**/routerMock.js jest.mock("next/router", () => ({ push: jest.fn(), back: jest.fn(), events: { on: jest.fn(), off: jest.fn(), }, beforePopState: jest.fn(() => null), useRouter: () => ({ push: jest.fn(), }), }));
- Add jest setup in jest config
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
- Import mocks you want setup global
import "./jest/__mocks__/routerMock";
Mock implementation
-
Mock implementation a hook to return expected value
const mockFunction = jest.fn(); jest.mock("next/navigation", () => ({ usePathname: mockFunction, })); test("test case", () => { mockFunction.mockImplementation(() => "some-thing-returned"); });
-
Mock axios
import axios from 'axios'; jest.mock("axios"); test("good response", () => { axios.get.mockImplementation(() => Promise.resolve({ data: {...} })); }); test("bad response", () => { axios.get.mockImplementation(() => Promise.reject({ ... })); })