情况:
我正在我的 Vue 应用程序中实现单元测试,使用带有 Jest 配置的 vue-test-utils。
当我测试简单的组件时,一切都很好。但是当我测试导入其他依赖项的组件时,测试失败。
配置:
Vue 版本:2.5.17
@vue/test-utils: 1.0.0-beta.20
cli-plugin-unit-jest: 3.0.3
babel-jest:23.0.1
错误信息:
确切的错误消息取决于我导入的依赖项。
例如 epic-spinners错误是:
SyntaxError: Unexpected token import
与 vue-radial-progress错误是:
SyntaxError: Unexpected token <
如何复制:
- 全新安装 vue(使用 Jest 作为单元测试套件)
- 运行示例测试,它应该通过
- 安装依赖项(例如:
npm install --save epic-spinners
) - 在HelloWorld组件中导入依赖
- 再次运行测试(不做任何更改)
如果我执行这些步骤,测试将失败并显示上述错误消息。
问题:
我如何处理 vue-test-utils/Jest 中的依赖项导入?
最佳答案
问题是某些模块可能无法正确编译。
解决方案是使用 transformIgnorePatterns Jest 设置的属性。也就是说,来自文档:
An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed.
就我而言,这就是我解决问题的方式:
transformIgnorePatterns: [
"node_modules/(?!epic-spinners|vue-radial-progress)"
],
编辑:
这是我的 jest.config.js
module.exports = {
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue'
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: [
"node_modules/(?!epic-spinners|vue-radial-progress)"
// "node_modules/(?!epic-spinners)",
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost/'
}
关于unit-testing - Vue-测试工具 | Jest : How to handle dependencies?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777978/