【问题标题】:Testing dynamic component using import() - TypeError: Path must be a string使用 import() 测试动态组件 - TypeError: Path must be a string
【发布时间】:2018-11-14 17:00:54
【问题描述】:

请帮忙,我在尝试使用 jest 为 vue js 动态组件创建测试时遇到此错误。 我正在使用 babel-plugin-syntax-dynamic-importbabel-plugin-transform-dynamic-import 与 babel ver > 7.0.0

● 测试套件无法运行

TypeError: Path must be a string. Received undefined

  at TestExclude.shouldInstrument (node_modules/test-exclude/index.js:77:31)
  at shouldSkip (node_modules/babel-plugin-istanbul/lib/index.js:59:21)
  at PluginPass.enter (node_modules/babel-plugin-istanbul/lib/index.js:74:15)
  at newFn (node_modules/@babel/core/node_modules/@babel/traverse/lib/visitors.js:193:21)
  at NodePath._call (node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:53:20)
  at NodePath.call (node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:40:17)
  at NodePath.visit (node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:88:12)
  at TraversalContext.visitQueue (node_modules/@babel/core/node_modules/@babel/traverse/lib/context.js:118:16)

这是我的 my-page.js 代码:

const MyComponent = () => import('src/components/MyComponent')
...
components: {
  MyComponent
},
...

myPage.spec.js 代码:

import { shallow } from 'vue-test-utils'
import MyPage from '@/pages/MyPage'

describe('MyPage.vue', () => {
  let component

  beforeEach(() => {
    component = shallow(MyPage, {
      ...
    })
    jest.resetModules()
    jest.clearAllMocks()
  })

  it('method#isEven', () => {
    let result = component.vm.isEven(2)
    expect(result).toBe(true)
  })
})

jest.conf.js 代码:

const path = require('path')

module.exports = {
  rootDir: path.resolve(__dirname, '../../'),
  moduleFileExtensions: [
    'js',
    'json',
    'vue'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  transform: {
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
  },
  testPathIgnorePatterns: [
    '<rootDir>/test/e2e'
  ],
  snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
  setupFiles: ['<rootDir>/test/unit/setup'],
  coverageDirectory: '<rootDir>/test/unit/coverage',
  collectCoverageFrom: [
    'src/**/*.{js,vue}',
    '!src/main.js',
    '!src/router/index.js',
    '!**/node_modules/**'
  ],
  testURL: 'http://localhost/unit-test'
}

我需要添加更多配置吗?

【问题讨论】:

    标签: vuejs2 vue-component jestjs babel-jest


    【解决方案1】:

    不需要使用 babel-plugin-syntax-dynamic-import,使用 babel-plugin-dynamic-import-node 代替。实现见https://jestjs.io/docs/en/webpack.html#using-with-webpack-2

    感谢https://github.com/facebook/jest/issues/5920

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 2017-03-19
      • 2012-06-14
      • 2021-06-25
      相关资源
      最近更新 更多