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
- install typescript as well as react and node types
npm install typescript @types/react @types/node -D
- 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
- create config files for typescript and babel
touch tsconfig.json
touch .babelrc
- add to the babel config file
{
"presets": ["next/babel"]
}
- create
jest.config.js
andjest.setup.ts
files
// jest.config.js
module.exports = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
};
// jest.setup.ts
import '@testing-library/jest-dom';
- start the app so next can configure typescript
npm run dev
BONUS
If you're going to use CSS modules, make sure you also include these steps:
- install
identity-obj-proxy
package
npm i identity-obj-proxy -D
- 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',
},
};
Now we are good to go, you can start changing your component from .js
to .tsx
and building your awesome app.
Top comments (8)
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:to your
jest.config.js
source: stackoverflow.com/a/51174924/3999031
Brillsies!!!
This helped me, thank you 🙏
Glad I could help :)
Exactly what I was looking for. Amazing!
Thank you a lot! Awesome! đź‘Źđź‘Źđź‘Ź
Glad I could help :)
Thank you so much!
looking for a solution that uses SWC and not babel