运行 Jest测试时为什么img标签src属性为空?

Why img tag src attribute is empty when run Jest test?

启动本地环境时图像成功呈现,但当我运行测试时,src 始终为空。

已经用 :src="require('...')" 试过了,但没用。

我错过了什么配置或其他东西?

这是我的相关配置、文件和版本:

//package.json
{
...
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "core-js": "^3.21.1",
    "vue": "^3.2.31"
  },
  "devDependencies": {
    "@babel/core": "^7.17.5",
    "@vue/cli-plugin-babel": "~5.0.1",
    "@vue/cli-service": "~5.0.1",
    "@types/jest": "^27.4.1",
    "@vue/test-utils": "^2.0.0-rc.18",
    "@vue/vue3-jest": "^27.0.0-alpha.4",
    "eslint-plugin-jest": "^26.1.1",
    "jest": "^27.5.1",
    "jest-transform-stub": "^2.0.0",
    "webpack": "^5.69.1"
  }
...
}
//jest.config.js
{
...
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/"
  },
  transform: {
    "^.+\.js$": "babel-jest",
    "^.+\.vue$": "@vue/vue3-jest",
    ".+\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
  },
}
//Image.Vue

<template>
  <img src="@/assets/foo.jpg" alt="">
</template>
...
//image.test.js
...
import MyImg from '../src/components/MyImg.vue'
test('img src attribute is', () => {
  const wrapper = shallowMount(MyImg)   
  expect(wrapper.find("img").attributes("src")).toBe("/img/foo.jpg")
})

我想通了:

问题在于 jest-transform-stub,因为它只是向 src 属性添加了一个空字符串。

解决方案来自https://jestjs.io/docs:

使用以下代码创建一个 fileTransformer.js 文件:

//fileTransformer.js

const path = require('path');

module.exports = {
  process(src, filename, _config, _options) {
    return `module.exports = ${JSON.stringify(path.basename(filename))};`;
  },
};

并用它修改 Jest 配置:

//jest.config.js

...
  transform: {
    //other configs you have
    ".+\.(css|styl|less|sass|scss|svg|png|jpg|jpeg|ttf|woff|woff2)$": "<rootDir>/path_to_file/fileTransformer.js",
  },
...

之后,预期的 .toBe 值将是:foo.jpg