-
SyntaxError: Unexpected token import
solution:
-
yarn add --dev babel-jest @babel/core @babel/preset-env
-
// babel.config.js module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current', //针对当前node版本进行编译,删除该行可能导致`npm start`报错 }, }, ], ], }; 复制代码
-
-
SyntaxError: Invalid or unexpected token @import
src
下新建__mocks__
文件夹,该文件夹下新建styleMock.js
,styleMock.js
内容为module.exports = {};
配置
jest.config.js
module.exports = { rootDir: 'src', moduleNameMapper: { '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js' } }; 复制代码
-
process.env.something
自定义环境变量丢失,值为undefined调用引用自定义环境的函数前,手动重新设置自定义环境变量,如下
// functions.js const variable = process.env.something; export function someFunction() { console.log(variable); console.log(process.env.something); } // functions.test.js import { someFunction } from './functions.js'; process.env.something = 'something'; await someFunction(); 复制代码
另外
functions.test.js
内someFunction的上一级作用域不为functions.js
的上一级作用域。以上代码打印undefined 'something' 复制代码
更复杂点的,比如重新设置自定义环境后还要还原,参考test process.env with Jest
-
Resolve alias in Jest not working
比如在
resolve->alis
中把src
设置成@
,用@
去引用文件时,yarn test
的时候会提示找不到相应文件。solution:
module.exports = { rootDir: 'src', moduleNameMapper: { '^@(/(shared)/(.*)$)': '<rootDir>$1 // shared为src下的文件夹,具体场景请更改正则表达式 } }; 复制代码
-
Jest matching objects in array
const data = [{ id: 1, name: 'hello' }, { id: 2, name: 'world' }] expect(data).toEqual( expect.arrayContaining([ expect.objectContaining({ id: expect.any(Number), name: expect.any(String) }) ]) ); 复制代码
-
jest macth type
expect.extend({ toBeType(received, argument) { const initialType = typeof received; const type = initialType === "object" ? Array.isArray(received) ? "array" : initialType : initialType; return type === argument ? { message: () => `expected ${received} to be type ${argument}`, pass: true } : { message: () => `expected ${received} to be type ${argument}`, pass: false }; } }); describe("testing extended expect", () => { it("tests normal types correctly", () => { expect("").toBeType("string"); expect({}).toBeType("object"); expect(1).toBeType("number"); }); it("tests array types correctly", () => { expect([]).toBeType("array"); }); it("works with promises", () => { expect(Promise.resolve([])).resolves.toBeType("array"); }); }); 复制代码
-
puppeteer安装
PUPPETEER_DOWNLOAD_HOST=https://storage.googleapis.com.cnpmjs.org cnpm i puppeteer
(否则chromium下载太慢) -
Cannot find module './types/standard' from 'index.js'
测试用例上使用
puppeteer
时,报以上错误。solution:
module.exports = { moduleFileExtensions: ['js', 'jsx', 'json'], // add 'json' }; 复制代码
转载于:https://juejin.im/post/5c64da15f265da2dc8494e55