Jest + Enzyme:如何测试图像 src?

IT技术 reactjs jestjs enzyme
2021-05-24 11:40:00

我有一个 Logo 组件:

import React from "react";
import logo from "assets/images/logo.png";

const Logo = () => {
  return <img style={{ width: 50 }} src={logo} alt="logo" />;
};

export default Logo;

测试文件:

import React from "react";
import Logo from "components/shared/Logo";

describe("<Logo />", () => {
  it("renders an image", () => {
    const logo = shallow(<Logo />);

    expect(logo.find("img").prop("src")).toEqual("blahh");
  });
});

但是当我运行测试时,出现了一些奇怪的错误:

$ NODE_PATH=src jest
 FAIL  src/tests/Logo.test.js
  ● <Logo /> › renders an image

    TypeError: val.entries is not a function

      at printImmutableEntries (node_modules/expect/node_modules/pretty-format/build/plugins/immutable.js:44:5)
      at Object.<anonymous>.exports.serialize (node_modules/expect/node_modules/pretty-format/build/plugins/immutable.js:178:12)

我应该如何测试图像 src === "assets/images/logo.png"?

4个回答

我想您__test__在 Logo components 附近目录中编写测试

无论如何,相对于您的测试文件导入您的“assets/images/logo.png”。

如果你的项目结构是这样的

Project
├── assets 
│   └── images
├       |
│       └── logo.png
├── src 
│   └── components
├       |── Logo.js 
│       └── __tests__
├           └── logo.test.js 
└ 

首先,就像我说的,通过键入将图像导入到 logo.test.js 中:

import React from 'react'; 
import {shallow} from 'enzyme';

import Logo from "./../Logo"; 
import logoImage from "./../../../assets/images/logo.png;

describe("<Logo />", () => {
    it("renders an image", () => {
        const logo = shallow(<Logo />);
        
        expect(logo.find("img").prop("src")).toEqual(logoImage);

     });
 });

出于某种原因,这些信息没有被清楚地突出显示。“与 wepack 集成”部分,它展示了如何使用以下命令自动模拟静态资产transform

如果 moduleNameMapper 不能满足您的要求,您可以使用 Jest 的转换配置选项来指定资产的转换方式。例如,一个返回文件基名的转换器(比如 require('logo.jpg'); 返回 'logo')可以写成:

包.json

{
  "jest": {
    "transform": {
      "\\.(js|jsx)$": "babel-jest",
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
    }
  }
}

文件转换器.js

const path = require('path');

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

因此,这将使您wrapper.props().src成为一个字符串(可用于任何类型的匹配器,如.toEqual)。这也意味着expect(wrapper).toMatchSnapshot()也像尊重图像路径的魅力一样工作。

[更新] 不要错过"babel-jest"在配置中为 JS/JSX 文件指定转换

/* **Image component** */
import React from "react";
import PropsTypes from "prop-types";
/** Image Component - This is shared component, You can use this component for rendering images
 * @param (string) altName
 * @param (string) fileName
 * @Return element
 */
const Image = props => {
  const { fileName, altName } = props;
  return <img src={`/images/${fileName}`} alt={altName}></img>;
};
/* Apply validation on Text Component */
Image.propTypes = {
  fileName: PropsTypes.string.isRequired,
  altName: PropsTypes.string.isRequired
};
Image.defaultProps = {
  fileName: "dummy.png",
  altName: "dummy"
};
export default Image;

/* Image.test.js */
import React from "react";
import { shallow } from "enzyme";
import Image from "./Image";

describe("Testing of Image component", () => {
  it("render image component with default value", () => {
    const wrapper = shallow(<Image />);
    expect(wrapper).toBeTruthy();
    expect(wrapper.find("img").length).toEqual(1);
  });
  it("render image component with props ", () => {
    const props = {
      fileName: "facebook.png",
      altName: "facebook"
    };
    const wrapper = shallow(<Image {...props} />);
    expect(wrapper).toBeTruthy();
    expect(wrapper.find("img").length).toEqual(1);
  });
});

像这样的东西..

import React from "react";
import Logo from "components/shared/Logo";

describe("<Logo />", () => {
  it("renders an image with src correctly", () => {
    const wrapper= shallow(<Logo src="yourlogo.png" />);
    expect(wrapper.html()).toEqual('<img src="yourlogo.png"/>'); // implement your ".toEqual(...)" to your Logo component result 
  });
});

或者,访问您的 src props:

const wrapper = mount(<Logo src="blah..."/>);
expect(wrapper.find({ prop: 'src' })).to.have.length(1); // or any other check you need 

http://airbnb.io/enzyme/docs/api/ReactWrapper/find.html