Search code examples
vue.jsjestjsvuejs3vue-test-utils

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


The image successfully rendered when started the local env but when I run the test the src is always empty.

Already tried it with :src="require('...')" but it didn't help.

What config or other thing I miss?

Here are my related configs, files and versions:

//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")
})

Solution

  • I have figured it out:

    The problem is with jest-transform-stub as it just adds an empty string to the src attribute.

    The solution comes from https://jestjs.io/docs:

    Create a fileTransformer.js file with the following code:

    //fileTransformer.js
    
    const path = require('path');
    
    module.exports = {
      process(src, filename, _config, _options) {
        return `module.exports = ${JSON.stringify(path.basename(filename))};`;
      },
    };
    

    and modify Jest config with it:

    //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",
      },
    ...
    

    and after this the expected .toBe value will be: foo.jpg