找不到映射为的模块~/ASSES/IMAGES/FLAGS/unfined.png

Could not locate module ~/assets/images/flags/undefined.png mapped as(找不到映射为的模块~/ASSES/IMAGES/FLAGS/unfined.png)

本文介绍了找不到映射为的模块~/ASSES/IMAGES/FLAGS/unfined.png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 console.error
    Error: Configuration error:
    
    Could not locate module ~/assets/images/flags/undefined.png mapped as:
    /home/user/Desktop/Workspace/porject/$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^~/(.*)$/": "/home/user/Desktop/Workspace/porject/$1"
      },
      "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>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '/^components/(.*)$/': '<rootDir>/components/$1',
    '^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与TypeScript和Compostion API一起使用

如何修复此问题?

推荐答案

ternary if解决问题ternary if

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

这篇关于找不到映射为的模块~/ASSES/IMAGES/FLAGS/unfined.png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:找不到映射为的模块~/ASSES/IMAGES/FLAGS/unfined.png

基础教程推荐