对于单元测试,我使用mocha + chai。
我使用"test": "mocha --require ts-node/register 'src/**/*spec.ts'"
运行命令。
当我在* spec.ts文件(例如import { expect } from 'chai';
)中使用导入
我收到错误SyntaxError: Cannot use import statement outside a module
我的tsconfig.json:
{
"compilerOptions": {
"baseUrl": "src",
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"lib": ["dom", "es2018"],
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true,
"removeComments": true,
"resolveJsonModule": true,
"strict": true,
"typeRoots": ["node_modules/@types"]
},
"exclude": ["node_modules"],
"include": ["src/**/*.ts"]
}
答案 0 :(得分:1)
您尝试过const expect = require('chai')
吗?
这是一种包装CommonJS中使用的模块的方法,该模块等效于import { expect } from 'chai';
。
答案 1 :(得分:1)
“ mocha”仅用于 commonJS 模块。您可以通过在node_modules / mocha中搜索README文件来找到它。
如果您想使用 esnext ,我建议您改为“开玩笑”。它与“摩卡咖啡”相差不大。
适合我的配置示例:
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
]
}
package.json
{
"name": "website",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test-watch": "npm run test -- --watch",
"pretty": "prettier --write \"**/*.js\""
},
"dependencies": {
"@material-ui/core": "^4.9.9",
"@material-ui/icons": "^4.9.1",
"next": "9.3.4",
"react": "16.13.1",
"react-dom": "16.13.1"
},
"devDependencies": {
"@types/jest": "^25.2.1",
"@types/node": "^13.11.0",
"@types/react": "^16.9.32",
"jest": "^25.2.7",
"prettier": "^2.0.2",
"ts-jest": "^25.3.1",
"ts-node": "^8.8.1",
"typescript": "^3.8.3"
}
}
jest.config.json
module.exports = {
roots: ["<rootDir>"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
testRegex: "(/tests/.*|(\\.|/)(test|spec))\\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
};