包含图像的 React 组件的 Mocha 测试失败

Mocha test failing for React component containing an image

我正在为 React 组件做单元测试。测试工作正常,除非有一个包含图像的组件。在这种情况下,组件测试永远不会 运行s,因为程序在测试开始之前就停止了 运行.

这是目录结构

data
- images.js
public
- images
  - photo.jpeg
src
- components
  - Photo.js
test
- components
  - Photo.spec.js
package.json

这是 package.json 文件

{
  "name": "image-test",
  "version": "1.0.0",
  "description": "just an image",
  "scripts": {
    "test": "NODE_ENV=production mocha './test/**/*.spec.js' --require @babel/register"
  },
  "dependencies": {
    "@babel/core": "^7.7.7",
    "@babel/helper-module-imports": "^7.7.4",
    "@babel/plugin-proposal-object-rest-spread": "^7.7.7",
    "@babel/plugin-transform-react-display-name": "^7.7.4",
    "@babel/polyfill": "^7.7.0",
    "@babel/preset-env": "^7.7.7",
    "@babel/preset-es2015": "^7.0.0-beta.53",
    "@babel/preset-react": "^7.7.4",
    "@babel/register": "^7.7.7",
    "@babel/runtime": "^7.7.7",
    "prop-types": "^15.7.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "expect": "^24.9.0",
    "mocha": "^7.0.0",
    "react-test-renderer": "^16.12.0"
  },
  "babel": {
    "presets": [
      "@babel/preset-react",
      "@babel/preset-env"
    ]
  }
}

这是组件 Photo.js

import React from 'react'
import PropTypes from 'prop-types'

export default class Photo extends React.Component {
  render() {
    const { image } = this.props
    return (
      <div>
    <img
      src={require(`../../public/images/${image.display_src}`).default}
      alt={image.caption} />
      </div>
    )
  }
}

Photo.propTypes = {
  image: PropTypes.object,
}

这是一个数据文件,其中包含一张图片的信息(实际实现的图片较多)。

const images = [
  {
    "display_src": "photo.jpeg",
    "caption": "The photo"
  },
]

export default images 

这里是组件测试文件Photo.spec.js

import React from 'react'
import TestRenderer from 'react-test-renderer'
import expect from 'expect'
import Photo from '../../src/components/Photo'

import images from '../../data/images'

describe('Photo Component', function () {
  it('should return a figure element', () => {
    const props = {
      image: images[0],
    }

    const result = TestRenderer.create(<Photo {...props} />)
    console.log(result)
    expect(result.type).toEqual('figure')
  })
})

当我运行用

测试
npm run test

我收到这个错误:

/Users/elbegom/Desktop/study/redux/state-management/simpletest/public/images/photo.jpeg:1
(function (exports, require, module, __filename, __dirname) { ����

这是完整输出的图像:

Screenshot of Mocha test error

我还在 github here

上放了一个最小的测试用例

有人能说说程序失败的原因吗?我也想知道如何解决这个问题,以及这是否是用图像测试组件的正确方法。

require 函数只加载 Javascript 文件,它不理解图像格式。如果要渲染图片,需要直接给src属性提供URl

export default class Photo extends React.Component {
  render() {
    const { image } = this.props;
    return (
      <div>
        <img src={`../../public/images/${image.display_src}`} alt={image.caption} />
      </div>
    );
  }
}

另请注意,src 路径应相对于呈现组件的网页 url,而不是 javascript 文件位置。