Vue Jest遇到了一个意外的标记,但没有指定这个标记。

3

我的几个单元测试无法运行,出现以下错误:

    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:

    SyntaxError: Unexpected token (9:80)

      at Parser.pp$4.raise (node_modules/vue-template-es2015-compiler/buble.js:2757:13)
      at Parser.pp.unexpected (node_modules/vue-template-es2015-compiler/buble.js:646:8)
      at Parser.pp$3.parseExprAtom (node_modules/vue-template-es2015-compiler/buble.js:2196:10)
      at Parser.<anonymous> (node_modules/vue-template-es2015-compiler/buble.js:6003:24)
      ...

我的Jest配置如下:
{
    moduleFileExtensions: [
        'js',
        'jsx',
        'json',
        // tell Jest to handle *.vue files
        'vue',
    ],
    transform: {
        // process *.vue files with vue-jest
        '^.+\\.vue$': require.resolve('vue-jest'),
        '.+\\.(css|styl|less|sass|scss|png|jpg|svg|ttf|woff|woff2|PNG)$':
            'jest-transform-stub',
        '^.+\\.jsx?$': require.resolve('babel-jest'),
    },
    transformIgnorePatterns: ['node_modules/(?!bootstrap)'],
    // support the same @ -> src alias mapping in source code
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
        '\\.(css|sass)$': 'identity-obj-proxy',
    },
    testEnvironment: 'jest-environment-jsdom-fifteen',
    // serializer for snapshots
    snapshotSerializers: ['jest-serializer-vue'],
    testMatch: [
        '**/tests/unit/**/*.spec.[jt]s?(x)',
        '**/__tests__/*.[jt]s?(x)',
    ],
    // https://github.com/facebook/jest/issues/6766
    testURL: 'http://localhost/',
    watchPlugins: [
        require.resolve('jest-watch-typeahead/filename'),
        require.resolve('jest-watch-typeahead/testname'),
    ]
}

我不知道如何调试这个错误,因为它似乎没有指定实际的非预期标记(除非是空格),也没有指向任何组件。

1个回答

3
修复了这个问题 - 它是由于在Vue HTML模板中使用可选链(object?.property)引起的。
我使用了以下语法的html元素:
<Component :name="data?.name" />

在我的单页组件的 HTML 模板中使用 ? 可选链操作符导致了 Unexpected token 错误,但它并没有指定 ? 是意外的标记。

1
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

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