I have a SearchBox component and want to make a test case for it.
SearchBox.tsx
import React from "react";
import IconButton from "@mui/material/IconButton";
import InputBase from "@mui/material/InputBase";
import Paper from "@mui/material/Paper";
import SearchIcon from "@mui/icons-material/Search";
function SearchBox() {
return (
<Paper
component="form"
sx={{ p: "2px 4px", display: "flex", alignItems: "center", width: 400 }}
>
<IconButton sx={{ p: "10px" }} aria-label="search">
<SearchIcon />
</IconButton>
<InputBase
sx={{ ml: 1, flex: 1 }}
placeholder="Search or start new chat"
inputProps={{ "aria-label": "search or start new chat" }}
/>
</Paper>
);
}
export default SearchBox;
I've tried to import the component in the SearchBox.test.ts.
import Searchbox from "src/components/SearchBox"
describe('first', () => {
it('', () => {...})
})
it just gives me an error. Seem like the absolute import is not working, but I'm not sure if it is Jest problem.
Cannot find module 'src/components/Searchbox' or its corresponding type declarations
jest.config.ts
export default {
roots: ["<rootDir>/src"],
moduleFileExtensions: ["js", "ts", "tsx"],
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"src/(.*)": "<rootDir>/src/$1",
},
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": [
"src"
],
"extends": "./tsconfig.paths.json"
}
tsconfig.path.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"src/*": ["*"]
}
}
}
Update 1
package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@mui/icons-material": "^5.8.4",
"@mui/material": "^5.8.5",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.41",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "^2.1.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/preset-typescript": "^7.17.12",
"jest": "^28.1.1",
"ts-node": "^10.8.1",
"typescript": "^4.7.4"
}
}