Member-only story

Test ts and tsx files in reactjs using jest

D
1 min readJan 24, 2024

--

Test driven development, the supposed gold standard for writing high quality. Couple this with typescript and we have the perfect blend of a strongly typed language with adequate testing. However, what they didn’t tell you is the level of set up related to get this running. Fret not, let’s run through it together.

First create a tsconfig.json

{
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react"
},
}

Second create a babel.config.json

{
"presets": [
"@babel/preset-react",
"@babel/preset-env"
]
}

Third create a jest.config.json

{
"preset": "ts-jest",
"transform": {
"^.+\\.(ts|tsx)?$": "ts-jest",
"^.+\\.(js|jsx)$": "babel-jest"
},
"moduleNameMapper": {
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.json"
},
"testEnvironment": "jsdom"
}

Fourth create a styleMock.json and insert the following:

{   
}

Fifth, import ts-jest by doing npm i ts-jest .

Sixth, run the tests by addding the test line below to package.json. Then do npm run test

  "scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},

--

--

D
D

Written by D

An aspiring Robotics Researcher. I am currently in my 4th year of undergraduate studies. I am working on optimising the ROS navigation packages. Follow 4 more!

No responses yet