【问题标题】:Jest + Enzyme: How to test an image src?Jest + Enzyme:如何测试图像 src?
【发布时间】:2018-06-22 07:22:52
【问题描述】:

我有一个 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"?

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    我假设您在徽标组件附近的 __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);
    
         });
     });
    

    【讨论】:

      【解决方案2】:

      由于某种原因,此信息未明确突出显示。 在'Integration with wepack' 部分显示了如何使用transform 自动模拟静态资产:

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

      package.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"
          }
        }
      }
      

      fileTransformer.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] 不要错过在配置中为 JS/JSX 文件指定 "babel-jest" 转换

      【讨论】:

        【解决方案3】:
        /* **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);
          });
        });
        

        【讨论】:

          【解决方案4】:

          像这样..

          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

          【讨论】:

            【解决方案5】:

            这对我有用...

            组件:

            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)

            【讨论】:

              【解决方案6】:
              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");
              })
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-09-14
                • 2018-12-16
                • 2018-11-09
                • 1970-01-01
                • 1970-01-01
                • 2023-03-06
                • 2019-01-29
                • 1970-01-01
                相关资源
                最近更新 更多