DEV Community

loading...
Cover image for Setup Next.js with Typescript , Jest and React Testing Library

Setup Next.js with Typescript , Jest and React Testing Library

maciekgrzybek profile image Maciek Grzybek Updated on ・2 min read

Why?

Next.js is a super cool React framework, that gives you an amazing developer experience. In this episode, I'll show you how to set it up with Typescript, Jest and React Testing Library.

Setup

To set up the project we'll need to follow these steps:

  • to create Next app, from your terminal run
npx create-next-app
Enter fullscreen mode Exit fullscreen mode
  • install typescript as well as react and node types
npm install typescript @types/react @types/node -D
Enter fullscreen mode Exit fullscreen mode
  • install jest, react testing library, babel-jest, @testing-library/jest-dom and types for jest
npm i jest @testing-library/react @types/jest babel-jest @testing-library/jest-dom @testing-library/user-event @testing-library/dom -D
Enter fullscreen mode Exit fullscreen mode
  • create config files for typescript and babel
touch tsconfig.json
touch .babelrc
Enter fullscreen mode Exit fullscreen mode
  • add to the babel config file
{
  "presets": ["next/babel"]
}
Enter fullscreen mode Exit fullscreen mode
  • create jest.config.js and jest.setup.ts files
// jest.config.js
module.exports = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
};
Enter fullscreen mode Exit fullscreen mode
// jest.setup.ts
import '@testing-library/jest-dom';
Enter fullscreen mode Exit fullscreen mode
  • start the app so next can configure typescript
npm run dev
Enter fullscreen mode Exit fullscreen mode

BONUS

If you're going to use CSS modules, make sure you also include these steps:

npm i identity-obj-proxy -D
Enter fullscreen mode Exit fullscreen mode
  • update jest.config.js file to look like this
module.exports = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
  moduleNameMapper: {
    '\\.(scss|sass|css)$': 'identity-obj-proxy',
  },
};

Enter fullscreen mode Exit fullscreen mode

Now we are good to go, you can start changing your component from .js to .tsx and building your awesome app.

Discussion (3)

pic
Editor guide
Collapse
kastinpl profile image
KASTIN.pl

it's good to mention also one more thing: if you use a tsconfig.json -> compilerOptions.baseUrl config for absolute paths feature, you have to add:

moduleDirectories: ['node_modules', 'src']
Enter fullscreen mode Exit fullscreen mode

to your jest.config.js

source: stackoverflow.com/a/51174924/3999031

Collapse
spences10 profile image
Scott Spence

Brillsies!!!

This helped me, thank you 🙏

Collapse
maciekgrzybek profile image
Maciek Grzybek Author

Glad I could help :)