问题描述
当我尝试运行测试时出现此错误...
> cross-env NODE_ENV=test jest "--projects" "./jest.config.test.js"
FAIL test <path>/schema.test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse,e.g. it's not plain JavaScript.
By default,if Jest sees a Babel config,it will use that to transform your files,ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules,see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed,you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
<path>/src/base.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import firebase from 'firebase/app';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/source-map-support/node_modules/source-map/lib/source-map-generator.js:8:17)
测试本身很简单
import schema from './schema';
describe('schema',() => {
it('should be valid schema',async () => {
expect.assertions(1);
const validSchema = {
budgetType: 'manual',};
await expect(schema.validate(validSchema)).resolves.toStrictEqual(
'Paul',);
});
});
我的 babel.config.js 文件
/* eslint-env node */
module.exports = function (api) {
const isDevelopmentEnvironment = api.env() === 'development';
const isCI = !!process.env.CI;
if (isCI && isDevelopmentEnvironment) {
console.warn('You are loading babel in development mode but on CI');
} else {
console.log(`Loading babel in "${api.env()}" mode`);
}
api.cache.using(() => process.env.NODE_ENV);
return {
presets: [
[
'@babel/preset-env',{
modules: false,loose: true,shippedProposals: true,useBuiltIns: 'entry',corejs: 3,},],'@babel/preset-react',plugins: [
'macros','syntax-async-functions',['@babel/plugin-transform-for-of',{ loose: false }],'@babel/plugin-transform-async-to-generator',[
'@babel/plugin-transform-arrow-functions',{ spec: true,loose: false },// Use built in `Object.assign`,otherwise Babel will include another polyfill.
// @see https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread#usebuiltins
[
'@babel/plugin-proposal-object-rest-spread',{ useBuiltIns: true },// Don't use loose mode,all iterables are assumed to be arrays.
// @see https://babeljs.io/docs/en/next/babel-plugin-transform-spread.html#loose
['@babel/plugin-transform-spread',[
'@babel/plugin-transform-runtime',{
absoluteRuntime: false,helpers: true,regenerator: true,useESModules: false,version: '7.0.0-beta.0',[
'module-resolver',{
root: ['.'],extensions: ['.js','.jsx'],alias: {
'^routes$': './src/routes/index.js','^validator$': './src/validator.js','^base$': './src/base.js','^api/(.+)': './src/api/\\1','^hooks/(.+)': './src/hooks/\\1','^routes/(.+)': './src/routes/\\1','^helpers/(.+)': './src/helpers/\\1','^components/(.+)': './src/components/\\1','^icons/(.+)': './src/components/icons/\\1','^assets/(.+)': './src/assets/\\1','^pages/(.+)': './src/pages/\\1','^store$': './src/store/index.js','^store/(.+)': './src/store/\\1','@babel/plugin-transform-react-jsx',['@babel/plugin-syntax-dynamic-import'],['transform-react-remove-prop-types'],env: {
production: {
plugins: ['transform-react-remove-prop-types'],development: {
sourceMaps: true,presets: [
[
'@babel/preset-react',{
development: true,runtime: 'automatic',importSource:
'@welldone-software/why-did-you-render',plugins: [
'@babel/plugin-transform-react-jsx-source','@babel/plugin-transform-react-display-name','react-refresh/babel',test: {
sourceMaps: true,plugins: [
'@babel/plugin-transform-modules-commonjs','@babel/plugin-transform-react-jsx-source',presets: [
[
'@babel/preset-env',{
modules: 'commonjs',// runtimeHelpers: true,// useBuiltIns: 'entry',targets: {
node: 'current',browsers: 'defaults,not dead',};
};
还有 jest.config.js
module.exports = {
displayName: 'test',// rootDir: 'src/',// rootDir: '.',clearMocks: true,errorOnDeprecated: true,testEnvironment: 'jest-environment-jsdom-sixteen',coverageDirectory: 'coverage',collectCoverageFrom: ['<rootDir>/src/**/*.{js,jsx}'],coveragePathIgnorePatterns: ['/node_modules/','/__mocks__/','/mocks/'],coverageThreshold: {
global: {
branches: 80,functions: 80,lines: 80,statements: -10,transform: {
/**
* Due the transform error
* @see https://github.com/facebook/jest/issues/8006#issuecomment-625927890
*/
'^.+\\.(js|jsx)$': ['babel-jest',{ rootMode: 'upward' }],setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],testMatch: ['<rootDir>/src/**/*.test.js?(x)'],notify: true,notifyMode: 'failure-change',globals: {},moduleFileExtensions: ['js','jsx','json'],moduleNameMapper: {
/**
* Due the transform error
* @see https://github.com/facebook/jest/issues/8006#issuecomment-609913705
*/
'@babel/core/lib/config/files/index-browser.js':
'@babel/core/lib/config/files/index.js','\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/__mocks__/fileMock.js','\\.(css|less|scss|sass)$': 'identity-obj-proxy',routes: ['<rootDir>/src/routes/index.js'],validator: ['<rootDir>/src/validator.js'],base: ['<rootDir>/src/base.js'],'api/(.*)': ['<rootDir>/src/api/$1'],'hooks/(.*)': ['<rootDir>/src/hooks/$1'],'routes/(.*)': ['<rootDir>/src/routes/$1'],'helpers/(.*)': ['<rootDir>/src/helpers/$1'],'components/(.*)': ['<rootDir>/src/components/$1'],'assets/(.*)': ['<rootDir>/src/assets/$1'],'pages/(.*)': ['<rootDir>/src/pages/$1'],store: ['<rootDir>/src/store/index.js'],'store/(.*)': ['<rootDir>/src/store/$1'],};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)