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

maciekgrzybek

Maciek Grzybek

Posted on September 25, 2020

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

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.

💖 💪 🙅 🚩
maciekgrzybek
Maciek Grzybek

Posted on September 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related