Jest + Enzyme: How to test an image src?

ぃ、小莉子 提交于 2019-12-04 02:23:38

I suppose that you write your tests inside a __test__ directory near Logo components .

Anyway, import your "assets/images/logo.png" relatively to your test file.

if your project structure is like this

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

First, Like I said import image into your logo.test.js by typing:

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);

     });
 });

For some reason this information is not clearly highlighted. In 'Integration with wepack' section it's displayed how to auto mock static assets with transform:

If moduleNameMapper cannot fulfill your requirements, you can use Jest's transform config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that require('logo.jpg'); returns 'logo') can be written as:

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)) + ';';
  },
};

So this would make your wrapper.props().src to be just a string(available for any kind matchers like .toEqual). Also it means expect(wrapper).toMatchSnapshot() also works like a charm respecting image path.

[upd] don't miss specifying "babel-jest" transformation for JS/JSX files in config

Something like this..

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 
  });
});

Or, to access your src prop:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!