{"id":22688325,"url":"https://github.com/emanuelefavero/next-jest-testing-library","last_synced_at":"2026-04-13T19:32:41.390Z","repository":{"id":155679948,"uuid":"629589678","full_name":"emanuelefavero/next-jest-testing-library","owner":"emanuelefavero","description":"This is a cheat sheet repo for Next.js + Jest + React Testing Library","archived":false,"fork":false,"pushed_at":"2023-04-28T18:21:38.000Z","size":478,"stargazers_count":36,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-29T15:32:26.564Z","etag":null,"topics":["functional-testing","jest","nextjs","react","react-testing-library","testing","unit-testing"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/emanuelefavero.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-18T16:03:33.000Z","updated_at":"2025-02-12T09:32:10.000Z","dependencies_parsed_at":null,"dependency_job_id":"3ebcc96e-3160-491d-a2b7-43ed64424170","html_url":"https://github.com/emanuelefavero/next-jest-testing-library","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/emanuelefavero/next-jest-testing-library","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-jest-testing-library","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-jest-testing-library/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-jest-testing-library/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-jest-testing-library/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/emanuelefavero","download_url":"https://codeload.github.com/emanuelefavero/next-jest-testing-library/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-jest-testing-library/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31768637,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-13T15:25:13.801Z","status":"ssl_error","status_checked_at":"2026-04-13T15:25:09.162Z","response_time":93,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["functional-testing","jest","nextjs","react","react-testing-library","testing","unit-testing"],"created_at":"2024-12-10T00:13:51.079Z","updated_at":"2026-04-13T19:32:41.313Z","avatar_url":"https://github.com/emanuelefavero.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Next.js + Jest + React Testing Library\n\nThis is a cheat sheet repo for Next.js + Jest + React Testing Library. Each page is a different topic\n\n\u003e Note: Check [this page](https://testing-library.com/docs/dom-testing-library/cheatsheet/) for a quick cheat sheet from the official react testing library docs\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## How to use\n\n- clone this repo and `cd` into it\n- run `npm install` to install dependencies\n- run `npm test` to run tests\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Create a new Next.js app with Jest and React Testing Library\n\n- run `mkdir` followed by the name of your project and `cd` into it, then:\n\n```bash\nnpx create-next-app --example with-jest .\n```\n\n- make sure to remove the `__tests__` folder if already there to clear the example tests\n- clear the `pages/index.js` boilerplate code\n- remove `.git` folder if you want to start fresh: `rm -rf .git`\n- initialize a new git repo: `git init` (`npm test` will fail if you don't do this)\n- run `npm test` to make sure everything is working\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Configure eslint with Jest and React Testing Library\n\n\u003e Note: For this to work you should already have eslint installed and configured in your project byt choosing it during the `create-next-app` setup\n\n- install eslint plugins for jest and react-testing-library:\n\n```bash\nnpm install --save-dev eslint-plugin-testing-library eslint-plugin-jest-dom\n```\n\n- add the following to your `.eslintrc` file:\n\n```json\n{\n  \"plugins\": [\"testing-library\", \"jest-dom\"],\n  \"extends\": [\"plugin:testing-library/react\"]\n}\n```\n\n\u003e Note: Check the `.eslintrc.json` file in this repo for a full example\n\n- be sure to have this rule on your `settings.json` file in vscode:\n\n```json\n\"editor.codeActionsOnSave\": {\n    \"source.fixAll.eslint\": true\n  }\n```\n\n\u003e Note: You can either put this on your global settings or on your project settings by adding a `.vscode` folder to your project and adding a `settings.json` file inside it\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Run Jest Tests\n\n```bash\nnpm test\n```\n\n### Jest commands\n\n- `jest --watch` - run tests in watch mode\n- `jest --watchAll` - run all tests in watch mode\n- `jest` - run all tests and exit\n- `jest --coverage` - run tests with coverage report\n- `jest --watch --coverage` - run tests in watch mode with coverage report\n\n#### Jest watch mode commands\n\n- `f` - run only failed tests\n- `o` - run only tests related to changed files\n- `p` - filter by a filename regex pattern\n- `t` - filter by a test name regex pattern\n- `q` - quit watch mode\n- `Enter` - trigger a test run\n- `a` - run all tests\n\n#### Jest test.only() and test.skip()\n\n- `test.only()` - run only this test\n- `test.skip()` - skip this test\n\nExample:\n\n```js\ntest.only('should render...', () =\u003e {\n  // ...\n})\n```\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## How does Jest watch mode work?\n\n- Jest will run all tests that have changed since the last commit. If you want to run all tests, you can press `a` to run all tests.\n- When a file is saved or a test file is changed, Jest will re-run the tests\n\n\u003e Note: If there are **no changes since the last commit**, **no tests will run**.\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## TDD (Test Driven Development)\n\n- Write tests before writing code\n- Write the minimum amount of code to make the tests pass\n- Refactor code as needed\n\n\u003e Note: Its is called \"red-green\" testing because the test initially fails (red) and then passes (green) after the code is written\n\n### Why TDD?\n\n- You don't need to manually test your code every time you make a change\n- You can refactor your code with confidence because you have tests to make sure nothing breaks\n- Writing tests before the code forces you to think about the code you are writing\n- Writing tests before the code feels part of the process, instead of a \"chore\" to do at the end\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Unit Testing vs Functional Testing\n\n#### **Unit testing** - tests individual units of code\n\n| Pros                      | Cons                                |\n| ------------------------- | ----------------------------------- |\n| Mock dependencies         | Further from how users interact     |\n| Easy to pinpoint failures | More likely to break in refactoring |\n\n#### **Functional testing** - tests how the app works from the user's perspective\n\n| Pros                        | Cons                    |\n| --------------------------- | ----------------------- |\n| Close to how users interact | More difficult to debug |\n| Robust tests                |                         |\n\n\u003e Note: react-testing-library is a functional testing library\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## render method\n\n#### import render\n\n```js\nimport { render } from '@testing-library/react'\nimport Component from './Component'\n```\n\n### use render\n\n```js\nrender(\u003cComponent /\u003e)\n```\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Testing Library screen methods\n\n#### import screen\n\n```js\nimport { screen } from '@testing-library/react'\n```\n\n### use screen\n\n```js\nconst button = screen.getByRole('button')\n```\n\n#### Commands\n\n\u003e e.g. `screen.queryByRole('button')` - returns a single element\n\n- `get` - expect an element to be in the DOM\n- `query` - expect an element not to be in DOM (useful for popovers etc...), returns null if not found\n- `find` - expect an element to be in the DOM, but wait for it to appear (useful for async data)\n\n#### All\n\n\u003e e.g. `getAllByRole('button')` - returns an array of all buttons in the DOM\n\nAdd `All` to the command to return an array of elements\n\n#### Query Type\n\n\u003e e.g. `getByRole('button')`\n\n- `ByRole` - query by role\n- `ByLabelText` - query by label text\n- `ByPlaceholderText` - query by placeholder text\n- `ByText` - query by text\n- `ByDisplayValue` - query by display value\n- `ByAltText` - query by alt text\n- `ByTitle` - query by title\n- `ByTestId` - query by test id\n\n## Testing Library Order of Priority\n\nTesting Library suggest to follow accessibility guidelines when writing tests. This means that you should use the following order of priority when querying the DOM:\n\n- `getByRole('button', { name: /click me/i })`\n- `getByLabelText('First Name')`\n- `getByPlaceholderText('Enter your first name')`\n- `getByText('Click me')`\n- `getByDisplayValue('John')`\n- `getByAltText('Profile picture')`\n- `getByTitle('Close')`\n- `getByTestId('my-element')`\n\n\u003e Note: You should only use `getByTestId` as a last resort. Assign `data-testid='my-element'` to the element that you need to find\n\n### Accessibility Roles\n\n- alert, alertdialog, application, article, banner, button, checkbox, columnheader, combobox, complementary, contentinfo, definition, dialog, directory, document, form, grid, gridcell, group, heading, img, link, list, listbox, listitem, log, main, marquee, math, menu, menubar, menuitem, menuitemcheckbox, menuitemradio, navigation, none, note, option, presentation, progressbar, radio, radiogroup, region, row, rowgroup, rowheader, scrollbar, search, searchbox, separator, slider, spinbutton, status, tab, tablist, tabpanel, textbox, timer, toolbar, tooltip, tree, treegrid, treeitem\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## js-dom Custom Matchers\n\n\u003e See: [https://github.com/testing-library/jest-dom](https://github.com/testing-library/jest-dom)\n\n- toBeDisabled\n- toBeEnabled\n- toBeEmptyDOMElement\n- toBeInTheDocument\n- toBeInvalid\n- toBeRequired\n- toBeValid\n- toBeVisible\n- toContainElement\n- toContainHTML\n- toHaveAccessibleDescription\n- toHaveAccessibleName\n- toHaveAttribute\n- toHaveClass\n- toHaveFocus\n- toHaveFormValues\n- toHaveStyle\n- toHaveTextContent\n- toHaveValue\n- toHaveDisplayValue\n- toBeChecked\n- toBePartiallyChecked\n- toHaveErrorMessage\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## userEvent\n\n`userEvent` is a library that provides a set of utilities to simulate user interactions with the DOM. It is a wrapper around `fireEvent` that provides a more natural API for interacting with the DOM.\n\n\u003e Note: `userEvent` always returns a Promise, so you must use `await` with it\n\n### userEvent Usage\n\n```js\n// ... other imports\nimport userEvent from '@testing-library/user-event'\n\ndescribe('Component', () =\u003e {\n  it('should do something', async () =\u003e {\n    // NOTE: Setup userEvent\n    const user = userEvent.setup()\n\n    render(\u003cComponent /\u003e)\n    const button = screen.getByRole('button')\n\n    await user.click(checkbox)\n  })\n})\n```\n\n\u003e Read This for more info: [https://testing-library.com/docs/ecosystem-user-event/](https://testing-library.com/docs/ecosystem-user-event/)\n\n### userEvent methods\n\n- `userEvent.click(element)` - click an element\n- `userEvent.hover(element)` - hover over an element\n- `userEvent.unhover(element)` - unhover over an element\n- `userEvent.type(element, text)` - type text into an element\n- `userEvent.clear(element)` - clear text from an input or textarea\n- `userEvent.selectOptions(element, values)` - select options in a select element\n- `userEvent.upload(element, fileOrFiles)` - upload a file or files to an element\n- `userEvent.tab()` - tab to the next focusable element\n- `userEvent.keyboard(text)` - type text using the keyboard\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Mock Service Worker\n\nMock Service Worker (MSW) is a service worker based library that allows you to intercept network requests and mock responses.\n\n### Install\n\n\u003e See: [https://mswjs.io/docs/getting-started/install](https://mswjs.io/docs/getting-started/install)\n\n```bash\nnpm install msw --save-dev\n```\n\n### Setup\n\n\u003e See: [https://mswjs.io/docs/getting-started/integrate/node](https://mswjs.io/docs/getting-started/integrate/node)\n\n- Add the following to `jest.setup.js`\n\n```js\nimport { server } from './mocks/server'\n// Establish API mocking before all tests.\nbeforeAll(() =\u003e server.listen())\n\n// Reset any request handlers that we may add during the tests,\n// so they don't affect other tests.\nafterEach(() =\u003e server.resetHandlers())\n\n// Clean up after the tests are finished.\nafterAll(() =\u003e server.close())\n\n// TIP: This file is similar to setupTests.js from create-react-ap\n```\n\n\u003e Note: Make sure to have imported `jest.setup.js` in `jest.config.js` like so `setupFilesAfterEnv: ['\u003crootDir\u003e/jest.setup.js'],`\n\n### Usage\n\n\u003e See: [https://mswjs.io/docs/getting-started/mocks/rest-api](https://mswjs.io/docs/getting-started/mocks/rest-api)\n\n- Create a `mocks` folder in the root of your project\n- Create a `server.js` file in the `mocks` folder\n- Add the following to `server.js`\n\n```js\nimport { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\n\n// This configures a request mocking server with the given request handlers.\nexport const server = setupServer(...handlers)\n```\n\n- Create a `handlers.js` file in the `mocks` folder\n- Add the following to `handlers.js`\n\n```js\nimport { rest } from 'msw'\nimport { apiURL } from '@/config'\n\nexport const handlers = [\n  rest.get(`${apiURL}/scoops`, (req, res, ctx) =\u003e {\n    return res(\n      ctx.json([\n        { name: 'Chocolate', imagePath: '/images/chocolate.png' },\n        { name: 'Vanilla', imagePath: '/images/vanilla.png' },\n      ])\n    )\n  }),\n  // ... other handlers\n]\n```\n\n- Now you can get fetched data from your mock server in your test files by using `await` and `findBy*` queries\n\n```js\nimport { render, screen } from '@testing-library/react'\nimport Options from './Options'\n\ntest('my test', async () =\u003e {\n  render(\u003cOptions optionType='scoops' /\u003e)\n\n  const scoopImages = await screen.findAllByRole('img', { name: /scoop$/i })\n  expect(scoopImages).toHaveLength(2)\n\n  const altTextArray = scoopImages.map((element: any) =\u003e element.alt)\n  expect(altTextArray).toEqual(['Chocolate scoop', 'Vanilla scoop'])\n})\n```\n\n**HOW DOES IT WORK?** When we run the test, if the component makes a request to the server, the request will be intercepted by Mock Service Worker (that we setup in jest.setup.js) and it will check if there is a handler for that same request (same url). IF there is, the mock request will be used instead of the real request\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Simulate Server Error Response\n\n- use `server.resetHandlers()` to setup a new behavior (e.g. return an error) for a route\n\n```js\nimport { render, screen, waitFor } from '@testing-library/react'\nimport { rest } from 'msw'\nimport { server } from '@/mocks/server'\nimport { apiURL } from '@/config'\nimport Component from './Component'\n\ntest('test error', async () =\u003e {\n  // setup the server to return an error for this route\n  server.resetHandlers(\n    rest.get(`${apiURL}/scoops`, (req, res, ctx) =\u003e {\n      return res(ctx.status(500))\n    })\n  )\n\n  render(\u003cComponent /\u003e)\n\n  // wait for the error message to show up\n  await waitFor(async () =\u003e {\n    const alerts = await screen.findAllByRole('alert')\n    expect(alerts).toHaveLength(1)\n  })\n})\n```\n\n\u003e Note: See Mock Service Worker section on this page for more info on how to setup the server\n\u003e\n\u003e TIP: you still need to add the error handling logic in your component\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Test components wrapped in a Provider (context)\n\n- To test components that are children of a Provider (components that use context) you need to wrap them with your Provider in your test file during rendering:\n\n```js\nrender(\u003cComponent /\u003e, {\n  wrapper: MyProvider,\n  ...options,\n})\n```\n\n\u003e Note: Since you would need to do so in every test file, it's better to create a custom render function that does this for you. See `test-utils.tsx` file in this project for an example\n\n### Create a custom render function with wrapped context\n\n\u003e See: [https://testing-library.com/docs/react-testing-library/setup](https://testing-library.com/docs/react-testing-library/setup)\n\n- Create a `test-utils.tsx` file in the root of your project or in the `src` folder\n\n```js\nimport { render } from '@testing-library/react'\nimport { OrderDetailsProvider } from '@/contexts/OrderDetails'\n\nconst renderWithContext = (ui: any, options?: any) =\u003e\n  render(ui, {\n    wrapper: OrderDetailsProvider,\n    ...options,\n  })\n\n// re-export everything\nexport * from '@testing-library/react'\n\n// override render method with render with context\nexport { renderWithContext as render }\n```\n\n- Now you can import your custom render function in your test files:\n\n```js\n// NOTE: you don't need to import render from @testing-library/react anymore\nimport { render, screen, waitFor } from '@/test-utils'\n\ntest('test', () =\u003e {\n  render(\u003cComponent /\u003e)\n\n  // ...\n})\n```\n\n\u003e Note: As you can see the only thing you need to do is to import your custom render function in `@/test-utils` instead of the one from `@testing-library/react`\n\u003e\n\u003e Note: You can also add other providers to your custom render function\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Debugging Tips\n\n- Use `debug()` to log the html of the component to the console\n\n```js\nimport { render, screen } from '@testing-library/react'\n\ntest('test', async () =\u003e {\n  render(\u003cComponent /\u003e)\n\n  // log the html of the component to the console\n  screen.debug()\n\n  // ...\n})\n```\n\n- Use logRoles(container) to log the roles of the elements in the container to the console\n\n```js\nimport { render, screen, logRoles } from '@testing-library/react'\n\ntest('test', async () =\u003e {\n  const { container }render(\u003cComponent /\u003e)\n\n  // log the roles of the elements in the container to the console\n  logRoles(container)\n\n  // ...\n})\n```\n\n- Use `console.log()` to log the html of the component to the console\n\n```js\nimport { render, screen } from '@testing-library/react'\n\ntest('test', async () =\u003e {\n  render(\u003cComponent /\u003e)\n\n  // log the html of the component to the console\n  console.log(screen.getByRole('alert'))\n\n  // ...\n})\n```\n\n- If `getBy*` fail than it is likely that the element is not rendered yet. Use `findBy*` instead\n- userEvent methods always need `await`\n- Use `test.only()` and `test.skip()` to run only one test or skip a test\n\n- Prevent `act()...` warning from showing up in the test console by using unmount\n\n```js\ntest('test', async () =\u003e {\n  const { unmount } = render(\u003cComponent /\u003e)\n\n  // ...\n\n  unmount()\n})\n```\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## jest.mock()\n\nUse `jest.mock()` to mock features and avoid errors when running tests\n\n- For example, `jest.mock()` can be used to mock props that are passed to a component\n\n```js\n\u003cComponent prop={jest.fn()} /\u003e\n```\n\n\u003e Note: `jest.mock()` doesn't actually do anything. It just tells jest to mock the prop to avoid errors\n\n- Another instance is when mocking modules such as `next/router`\n\n```js\nimport { useRouter } from 'next/router'\n\njest.mock('next/router', () =\u003e ({\n  useRouter: jest.fn(),\n}))\n```\n\n\u003e Note: This will prevent errors related to `useRouter` not being available in the test environment\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## Resources\n\n- [Next.js Testing](https://nextjs.org/docs/testing)\n- [Testing Library Cheat Sheet](https://testing-library.com/docs/react-testing-library/cheatsheet/)\n- [userEvent](https://testing-library.com/docs/ecosystem-user-event/)\n- [Testing Library Queries](https://testing-library.com/docs/queries/about/)\n- [Testing Library Order of Priority](https://testing-library.com/docs/queries/about/#priority)\n- [w3c Accessibility Roles](https://www.w3.org/TR/wai-aria/#role_definitions)\n- [getByTestId](https://testing-library.com/docs/queries/bytestid/)\n- [Mock Service Worker](https://mswjs.io/docs/getting-started/install)\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n## License\n\n- [MIT](LICENSE.md)\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n[**Go To Top \u0026nbsp; ⬆️**](#how-to-use)\n\n```\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femanuelefavero%2Fnext-jest-testing-library","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femanuelefavero%2Fnext-jest-testing-library","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femanuelefavero%2Fnext-jest-testing-library/lists"}