【问题标题】:Jest failing to even run a test suite for component that imports async functionJest 甚至无法为导入异步功能的组件运行测试套件
【发布时间】:2020-08-21 16:12:53
【问题描述】:

我已将一个项目从 angularjs 移至 Vue。移动它后,我试图用玩笑添加单元测试。我已经对一些较小的组件和服务进行了测试,它们按预期工作,没有任何问题。我现在正在尝试将测试添加到一些稍微复杂的组件中,现在我仅针对该测试套件出现错误。错误如下。

E:\Development\work\project\node_modules\@babel\runtime\helpers\esm\asyncToGenerator.js:17
    export default function _asyncToGenerator(fn) {
    ^^^^^^

    SyntaxError: Unexpected token 'export'

我要测试的组件有几个数据属性和子组件。

基本要点是

<template>
<div>
  <div v-if="allowed">...</div>
  <ChildComponent />
</div>

<script>
  import ChildComponent from './ChildComponent';
  import {getIsAllowed} from './allowed.service.js';

  export default {
    name: 'Parent',
    data() {
      return {
        allowed: getIsAllowed();
      }
    }
</script>

还有更多,但与我面临的问题无关。

ChildComponent 是问题所在。它类似于以下内容。

<template>
<div>...</div>
</template>

<script>
import {functionThatCallsAyncFunction} from 'fileThatContainsAsyncFunctions'
</script>

我的测试脚本如下

import {mount} from '@vue/test-utils';
import Parent from './Parent';

describe('my tests', () => {
  test('verify tests run', () => {
    expect(true).toBe(true);  
  })
})

这会导致我看到的错误。

我可以删除 Parent 的导入以摆脱错误。

我还可以从父组件中删除子组件的导入以修复错误。

我也可以去掉Child中调用异步函数的函数的导入来修复错误。

我可以将函数从 async/await 更改为使用 .then() 并且它会起作用。

shallowMount 和存根无效,因为测试会在它到达该点之前爆炸。

一定是我遗漏了一些东西,导致异步函数根本无法运行。我已经搞砸了两天了,谷歌提供了很多想法,但没有一个奏效。

我的相关 package.json 部分

"scripts" : {
  "test": "jest --config=jest.conf.js"
},
"devDependencies" : {
    "@babel/core": "^7.1.6",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/preset-env": "^7.1.6",
    "@vue/babel-preset-app": "^3.11.0",
    "@vue/test-utils": "^1.0.0-beta.26",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.6",
    "babel-loader": "^8.0.4",
    "jest": "^23.6.0",
    "jest-serializer-vue": "^2.0.2",
    "vue-jest": "^3.0.1"
}

jest.conf.js 很简单

const {defaults} = require('jest-config');
module.exports = {
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'vue'],
  transform: {
    ".*\\.(vue)$": "vue-jest",
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
  },
  'setupFiles': ['./tests/setup.js']
};

我的 babel.config.js 也是如此

module.exports = {
  presets: [
    '@vue/app',
    ['@babel/preset-env', {targets: { node: 'current'}}],
  ],
};

如果需要任何其他信息,我很乐意提供。这把我逼到了墙角。希望有人有一些想法可以帮助实现我所期望的工作。

提前致谢。

【问题讨论】:

    标签: unit-testing vue.js npm jestjs babeljs


    【解决方案1】:

    您可以尝试告诉 Jest 转译有问题的节点模块。有关完整说明,请参阅https://github.com/facebook/jest/issues/2550#issuecomment-381718006

      transformIgnorePatterns: [
        '/node_modules/(?!transpile-me|transpile-me-too).+(js|jsx)$'
      ],
    

    还有https://jestjs.io/docs/en/configuration.html#transformignorepatterns-arraystring

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2019-10-21
      • 2021-03-17
      • 2020-11-25
      • 2018-10-14
      • 2019-12-13
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多