Jest +酶:如何测试图像源代码?

tjrkku2a  于 2023-03-06  发布在  Jest
关注(0)|答案(6)|浏览(253)

我有一个徽标组件:

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)

我应该如何测试图像源代码===“assets/images/logo.png”?

g6baxovj

g6baxovj1#

我假设您在Logo组件附近的__test__目录中编写测试。
无论如何,导入与测试文件相关的“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);

     });
 });
11dmarpk

11dmarpk2#

upd 2023.正如@tomhughes所指出的,Jest 28在模拟转换方面有不同的逻辑:www.example.comhttps://jestjs.io/docs/28.x/upgrading-to-jest28#transformer
由于某些原因,此信息没有清楚地突出显示。在"与wepack集成"部分,显示了如何使用transform自动模拟静态资产:
如果moduleNameMapper不能满足你的要求,你可以使用Jest的transform配置选项来指定资产如何转换,例如,一个返回文件基本名称的转换器(比如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()也像一个魅力尊重图像路径。
[upd]不要错过在config中为JS/JSX文件指定"babel-jest"转换

ghg1uchk

ghg1uchk3#

/* **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);
  });
});
3yhwsihp

3yhwsihp4#

像这样的事...

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属性:

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

nzk0hqpo

nzk0hqpo5#

"* 这对我很有效**
组件:

function Header() {
        return (
            <div className="header">
                <img src="images/logo.png" alt="no logo found"/>
            </div>
        )
    }

试验:

it('should set logo image src correctly', () => {
        const logoImg = mountedHeader.find('img')
        expect(logoImg.getElement(0).props.src).toEqual("images/logo.png")
    });

https://acloud.guru/forums/serverless-portfolio-with-react/discussion/-KxEN_3qG3G9oxSHjyAN/Testing%20React%20-%20Testing%20images%20using%20expect(image.node.props.src)

nc1teljy

nc1teljy6#

describe("CharacterInfo", () => {
  const data={
    image:"ricky.jpg",
  }  
  it("should renders img src", () => {
     const wrapper=shallow(<CharacterInfo image={data.image}/>);
   });
  const imgSrc= wrapper.find("img").prop('src');
  expect(imgSrc).toBe("ricky.jpg");
})

相关问题