找不到模块 ~/assets/images/flags/undefined.png 映射为

Could not locate module ~/assets/images/flags/undefined.png mapped as

我有一些 img 标签,我用 require 动态地址填充它,它在组件中按预期工作但是当我为它编写测试时抛出这个错误

 console.error
    Error: Configuration error:
    
    Could not locate module ~/assets/images/flags/undefined.png mapped as:
    /home/user/Desktop/Workspace/porject/.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^~\/(.*)$/": "/home/user/Desktop/Workspace/porject/"
      },
      "resolver": undefined
    }
        at createNoMappedModuleFoundError (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:579:17)
        at Resolver.resolveStubModuleName (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:541:19)
        at Resolver.getMockModule (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:380:31)
        at Resolver._isModuleResolved (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:477:42)
        at Resolver._getAbsolutePath (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:455:17)
        at Resolver.getModuleID (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:424:31)
        at Runtime._shouldMock (/home/user/Desktop/Workspace/porject/node_modules/jest-runtime/build/index.js:1917:37)
        at Runtime.requireModuleOrMock (/home/user/Desktop/Workspace/porject/node_modules/jest-runtime/build/index.js:1204:14)
        at Proxy.render (/home/user/Desktop/Workspace/porject/components/newComponents/global/ChangeLanguage/index.vue:2903:14)
        at /home/user/Desktop/Workspace/porject/node_modules/@vue/composition-api/dist/vue-composition-api.common.js:1891:35

      at logError (node_modules/vue/dist/vue.common.dev.js:1902:13)
      at globalHandleError (node_modules/vue/dist/vue.common.dev.js:1893:3)
      at handleError (node_modules/vue/dist/vue.common.dev.js:1853:5)
      at VueComponent.Vue._render (node_modules/vue/dist/vue.common.dev.js:3570:7)
      at VueComponent.updateComponent (node_modules/vue/dist/vue.common.dev.js:4078:21)
      at Watcher.get (node_modules/vue/dist/vue.common.dev.js:4490:25)
      at Watcher.run (node_modules/vue/dist/vue.common.dev.js:4565:22)

这是一个测试文件:

import { createLocalVue, shallowMount } from '@vue/test-utils'
import Vuex from 'vuex'
import { $axios } from '~/test/unit/__mocks__/util'
import storeConfig from '~/test/unit/__mocks__/store'
import ChangeLanguage from '~/components/global/ChangeLanguage/index.vue'

const localVue = createLocalVue()
localVue.use(Vuex)

// eslint-disable-next-line import/no-named-as-default-member
const store = new Vuex.Store({
  modules: {
    index: {
      state: storeConfig().modules.index.state,
      getters: storeConfig().modules.index.getters,
      mutations: storeConfig().modules.index.mutations,
      actions: storeConfig().modules.index.actions,
      namespaced: false,
    },
  },
})

describe('global/changeLanguage.vue', () => {
  beforeEach(() => {
    console.error = jest.fn()
  })

  const wrapper = shallowMount(ChangeLanguage, {
    store,
    localVue,
    props: {
      visibility: { default: false },
    },
    mocks: {
      $axios,
    },
  })
  test('checks if visibility changes and event emit', async () => {
    await wrapper.setData({ isLanguagesVisible: true })
    await wrapper.find('[data-test="change-visibility"]').trigger('click')
    expect(wrapper.emitted()).toHaveProperty('changeVisibility')
  })
})

这里是组件代码:

<template>
  <div>
    <img
      :src="require(`~/assets/images/flags/${selectedLanguage.flagCode}.png`)"
      :alt="selectedLanguage.name"
      class="rounded-md w-8 h-6"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from "@nuxtjs/composition-api";
import { Language } from "~/types/components/layouts";
export default defineComponent({
  setup() {
    const selectedLanguage = ref<Language>({
      code: "en",
      name: "English",
      link: "/",
      flagCode: "us",
    });
    return {
      selectedLanguage,
    };
  },
});
</script>

这里是 jest.config.js 文件:

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/',
    '^~/(.*)$': '<rootDir>/',
    '/^components/(.*)$/': '<rootDir>/components/',
    '^vue$': 'vue/dist/vue.common.js',
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
  transform: {
    '^.+\.ts$': 'ts-jest',
    '^.+\.js$': 'babel-jest',
    '.*\.(vue)$': 'vue-jest',
    '\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/test/unit/fileTransformer.js',
  },
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/components/**/*.vue',
    '<rootDir>/pages/**/*.vue',
  ],
  testEnvironment: 'jsdom',
  setupFiles: ['<rootDir>/test/unit/setup.js'],
}

setup.js文件:

import Vue from 'vue'
import { config } from '@vue/test-utils'
import * as CompositionApi from '@nuxtjs/composition-api'
Vue.use(CompositionApi)

Vue.config.silent = true

// Mock some of global components 
config.stubs['nuxt-link'] = true
config.stubs['client-only'] = true
config.stubs.fa = true
// Mock some of global methods
config.mocks.$t = (i) => i
config.mocks.t = (i) => i
config.mocks.localePath = (i) => i
config.mocks.switchLocalePath = (i) => i

fileTransformer.js文件:

const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  },
};

package.json文件

{
  "name": "project",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
    "lint": "npm run lint:js",
    "test": "jest --watch"
  },
  "dependencies": {
    "@fortawesome/free-brands-svg-icons": "^5.15.4",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/composition-api": "^0.30.0",
    "@nuxtjs/i18n": "^7.0.3",
    "@nuxtjs/pwa": "^3.3.5",
    "cookie-universal-nuxt": "^2.1.5",
    "core-js": "^3.15.1",
    "gsap": "^3.8.0",
    "nuxt": "^2.15.7",
    "nuxt-fontawesome": "^0.4.0",
    "vue": "^2.6.14",
  },
  "devDependencies": {
    "@babel/eslint-parser": "^7.14.7",
    "@nuxt/types": "^2.15.7",
    "@nuxt/typescript-build": "^2.1.0",
    "@nuxtjs/eslint-config-typescript": "^6.0.1",
    "@nuxtjs/eslint-module": "^3.0.2",
    "@nuxtjs/tailwindcss": "^4.2.0",
    "@types/jest": "^27.0.2",
    "@vue/test-utils": "^1.2.1",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^27.0.5",
    "eslint": "^7.29.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-nuxt": "^2.0.0",
    "eslint-plugin-vue": "^7.12.1",
    "fibers": "^5.0.0",
    "jest": "^27.0.5",
    "postcss": "^8.3.5",
    "prettier": "^2.3.2",
    "sass": "^1.42.1",
    "sass-loader": "^10.2.0",
    "ts-jest": "^27.0.3",
    "vue-jest": "^3.0.4",
    "vuex": "^3.6.2"
  }
}

我正在使用带有打字稿和组合的 nuxt 2 API

我该如何解决这个问题?

问题已解决 ternary if:

<img
   :src="
     selectedLanguage.flagCode
       ? require(`~/assets/images/flags/${selectedLanguage.flagCode}.png`)
       : ''
   "
   class="rounded-md w-8 h-6"
 />