测试React API - Unexpected Token错误

3
我有一个使用create-react-app创建的基本React应用程序。我正在尝试使用Pact开始使用Javascript实现指南对我的API进行合同测试。
我已经按照上面链接中的步骤完全操作,并创建了一个基本测试,它基本上什么都不做,只是为了让我能够运行测试。
import { Pact } from '@pact-foundation/pact';

it('works', () => {
  expect(1).toEqual(1);
});

在运行npm run pactTest时,我收到了以下错误信息:
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:
 • 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/to/file.test.pact.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Pact } from '@pact-foundation/pact';
                                                                                                ^

SyntaxError: Unexpected token {

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

如果我将导入行更改为:const Pact = require('@pact-foundation/pact');,那么它就可以运行了。
问题在于,我不能像这个虚拟示例一样仅使用require,因为我在整个React项目中都使用import
我肯定错过了其他东西,因为Javascript实现指南使用的是import { Pact } from '@pact-foundation/pact';

感谢 @darkpool(同时也抱歉),该示例默认使用ES6语法(需要使用Babel等工具进行转译)。我已更新文档以帮助未来的其他人。 - Matthew Fellows
1个回答

1
在jest.config.js中的transform对象之后添加以下配置。
  '^.+\\.js$': 'babel-jest

下面是你参考的例子。
  module.exports = {
     moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
     transform: {
         '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
         'jest-transform-stub',
         '^.+\\.(js|jsx)?$': 'babel-jest'
     },
     moduleNameMapper: {
         '^@/(.*)$': '<rootDir>/src/$1'
     },
     snapshotSerializers: ['jest-serializer-vue'],
        testMatch: [
            '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
     ],
     transformIgnorePatterns: ['<rootDir>/node_modules/']
  };

不幸的是,我仍然遇到相同的错误。我还能尝试些什么吗? - darkpool
好的,请尝试运行以下命令:node node_modules/.bin/jest --clearCache - Hemadri Dasari
1
谢谢,已经解决了。我还需要创建一个.babelrc文件,其中包含{"presets": ["env", "react"]} - darkpool
哦,你以前没有做过这个。很好发现。继续学习,继续编码 :) - Hemadri Dasari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接