来自测试库的方法render/rect与我的组件不匹配



我正试图使用jest/testing库在我的nextJS应用程序中进行测试,当我将组件放入呈现方法中时,它抱怨道,这是我在接下来的第一次使用jest/areact测试,我遵循了文档,但它仍然不起作用:

错误:

SyntaxError: C:UsersgabriOneDriveDocumentosnextJSno_rolesrctestsindex.spec.ts: Unexpected token, expected "," (7:21)     
5 |
6 |     it ('Should open home', () => {
>  7 |         render(<MyApp/>)
|                      ^
8 |     })
9 | });
10 |
at Object._raise (node_modules/@babel/parser/src/parser/error.js:147:45)
at Object.raiseWithData (node_modules/@babel/parser/src/parser/error.js:142:17)
at Object.raise (node_modules/@babel/parser/src/parser/error.js:91:17)
at Object.unexpected (node_modules/@babel/parser/src/parser/util.js:175:16)
at Object.expect (node_modules/@babel/parser/src/parser/util.js:135:28)
at Object.tsParseDelimitedListWorker (node_modules/@babel/parser/src/plugins/typescript/index.js:421:16)
at Object.tsParseDelimitedList (node_modules/@babel/parser/src/plugins/typescript/index.js:376:14)
at Object.tsParseBracketedList (node_modules/@babel/parser/src/plugins/typescript/index.js:448:27)
at Object.tsParseTypeParameters (node_modules/@babel/parser/src/plugins/typescript/index.js:555:26)
at node_modules/@babel/parser/src/plugins/typescript/index.js:2902:31

index.spect.ts:

import {render, screen} from '@testing-library/react';
import MyApp from '../pages/_app'
describe('New Test', () => {
it ('Should open home', () => {
render(<MyApp/>)
})
});
export {};

jest.config.js:

module.exports = {
testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
moduleNameMapper: {
'^@/components/(.*)$': '<rootDir>/components/$1',
},
transform: {
'^.+\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
collectCoverageFrom: ['components/**/*.ts', 'pages/**/*.ts'],
coverageReporters: ['lcov', 'text'],
};

babel.config.js:

module.exports = {
presets: [
'@babel/preset-typescript',
'next/babel'
]
}

setupTest.js:

import '@testing-library/jest-dom';

package.json:

{
"name": "no_role",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest --watch"
},
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"@material-ui/icons": "^4.11.2",
"@mui/icons-material": "^5.2.5",
"@mui/material": "^5.2.5",
"next": "12.0.7",
"primeicons": "^5.0.0",
"primereact": "^7.1.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-lottie": "^1.2.3",
"react-transition-group": "^4.4.2"
},
"devDependencies": {
"@babel/preset-typescript": "^7.16.7",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@types/jest": "^27.4.0",
"@types/react": "^17.0.38",
"@types/react-lottie": "^1.2.6",
"eslint": "8.5.0",
"eslint-config-next": "12.0.7",
"jest": "^27.4.7",
"typescript": "^4.5.4"
}
}

将文件重命名为index.spec.tsx

如果有人也有这个问题,这对我来说很有效:

// jest.config.js
modulePaths: [
"<rootDir>"
],

最新更新