Jest目前无法通过测试,因为它找不到组件内部调用的模块:
FAIL tests/Unit/VHeaderBar.spec.ts
● Test suite failed to run
Cannot find module '@@/public/assets/images/placeholder.png' from 'VHeaderBar.vue'
at Resolver.resolveModule (node_modules/jest-runtime/node_modules/jest-resolve/build/index.js:221:17)
at src/components/VHeaderBar.vue:687:18
at Object.<anonymous> (src/components/VHeaderBar.vue:749:3)
案例
在 NuxtJs 中,@@
标记指向 root 目录,因为在最终解决方案中,我们要将图像存储在公用文件夹或存储文件夹中,位于项目的根目录。
运行测试时,玩笑检查src
文件夹,然后尝试挂载从根目录存储的图像,找不到它们。
我尝试了多种解决此问题的方法,但似乎找不到解决方法。 这是我已经尝试过的内容的简短列表:
- 使用Jest配置文件中的
regex
选项,更改moduleNameMapper
来检查图像文件并将其引导到正确的文件夹。 - 我在Stack上阅读了一些有关使用“模拟”文件夹的内容,该文件夹通过javascript导出图像文件,但这没用。
- 使用Jest配置文件中的
modulePaths
选项。 - 在
tsconfig.js
中为 assets 文件夹创建一个别名,并在moduleNameMapper
中使用它
- 在VueJS组件和测试文件中尝试了另一种方法来加载资产,这破坏了编译过程(因此我将其还原了)。
当前Jest配置文件
module.exports = {
moduleFileExtensions: [
"ts","tsx","vue","js","json"
],watchman: false,moduleNameMapper: {
"/\.(gif|jpg|jpeg|tiff|png)$/i": "<rootDir>/public/assets/images/$1","^@/(.*)$": "<rootDir>/src/$1","^~/(.*)$": "<rootDir>/src/$1","^~~/(.*)$": "<rootDir>/src/$1"
},transform: {
// process js with `babel-jest`
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",// process `*.vue` files with `vue-jest`
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",// process `*.ts` files with `ts-jest`
"^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest",},snapshotSerializers: [
"<rootDir>/node_modules/jest-serializer-vue"
],collectCoverage: true,collectCoverageFrom: [
"<rootDir>/src/components/**/*.vue","<rootDir>/src/pages/**/*.vue","<rootDir>/src/layouts/**/*.vue"
],testMatch: [
'**/tests/Unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],}
当前文件夹结构(仅用于测试的文件夹)
project folder
- public
-- assets
--- **images**
- src
-- components
--- **mounted component** (works)
- tests
-- Unit
--- mountedComponent.spec.ts
有什么建议吗?
我可以修复jest.config
吗?
语法是否有问题?
我必须修复tsconfig
吗?