首页 > 解决方案 > 测试导入图像的组件时出现“SyntaxError: Invalid or unexpected token”

问题描述

我正在为一个组件构建一个测试,该组件从常量文件中调用图像的 url。该组件工作正常,但是当我运行测试时出现此错误:

SyntaxError: Invalid or unexpected token
61 |     image: require('~/assets/right_facing_bird_in_tree.png'),
   |            ^

我不知道为什么常量文件上的 require 语句对开玩笑无效,但我需要它来正确渲染图像。

组件.vue

<template>
  <div>
    <div v-if="content.image" class="staff-photo">
      <img
        :id="content.identifier"
        :src="content.image"
        :style="{ height: content.imageHeight }"
      />
    </div>
  </div>
</template>

<script>
export default {
  props: ['content']
};
</script>

常量.js

export const HOMEPAGE_CONTENT = {
  huitzi: {
    image: require('~/assets/right_facing_bird_in_tree.png'),
    imageHeight: '340px',
    title: 'We are ',
    typedWords: [
      'UX Designers.',
      'Salesforce Developers.',
      'Software Engineers.',
      'Data Scientists.'
    ],
    text: 'But we are SO much more than that.',
    identifier: 'huitzi',
    hasBorderBottom: false,
    contentType: MAIN_PAGE_CONTENT_TYPE
  }
}

jest.config.js

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js'
  },
  moduleFileExtensions: [
    'js',
    'vue',
    'json'
  ],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/components/**/*.vue',
    '<rootDir>/pages/**/*.vue'
  ]
}

标签: javascriptvue.jsjestjs

解决方案


推荐阅读