Jest continues after running TypeScript single tests and increasing coverage
Cannot use import statement outside a module
Jest itself supports ESM, that is, a single test can be written this way
// src/lib/lite-lodash.js
export isPromise(.){... }Copy the code
// test/lib/lite-lodash.test.js
import { isPromise } from '.. /.. /src/lib/lite-lodash'
describe(...)
Copy the code
An error is reported when lite-lodash.js says import XX from YY. In fact, Babel does not recognize the import of the file under test.
Cannot use import statement outside a module
solution
Step 1: Install Babel-Jest
Step 2: Touch babel.config.js
// Only used by Jest should not affect business code building!
module.exports = { presets: ['@babel/preset-env']};Copy the code
Step 3: jest.config.js
module.exports = {
transform: {
"^.+\\.(js|jsx)$": "babel-jest",}};Copy the code
alias
The config file alias alis can solve the problem of import requiring the mental calculation of the path, we often use in Webpack or TS development experience optimization measures, such as
// jsconfig.json
{
"compilerOptions": {
"checkJs": true."target": "es2015"."moduleResolution": "node"."resolveJsonModule": true."baseUrl": "."."paths": {
"@ / *": ["./src/*"]}},"exclude": ["dist"."node_modules"."**/node_modules/*"]}Copy the code
But the trouble is if the file you test contains
import '@/common/lib/xxx'
Copy the code
Jest complains that it can’t find the file
Cannot find module ‘@/common/tools/format’ from ‘test/common/tools/url.test.js’
solution
jest.config.js
+ 'moduleNameMapper': {
+ '^@/(.*)': '
/src/$1',
+},
Copy the code
Cannot read property ‘cwd’ of undefined
Jest error:
Test suite failed to run
TypeError: Cannot read property ‘cwd’ of undefined
at Object.process (node_modules/babel-jest/build/index.js:325:33)
solution
"Babel - jest" : "^ 27.0.6",- "jest", "^ 26.6.3",
+ "jest" : "^ 27.0.6",
Copy the code
conclusion
Jest support for ESM by default is great, but support is incomplete and Babel is needed. Mocha supports ESM with the following modifications to make it more convenient.
Install esM, then modify test:
"scripts": {
+ "test": "node -r esm ./node_modules/.bin/mocha"
Copy the code
reference
How to resolve “Cannot use import statement outside a module” in jest