Search code examples
reactjsjestjsenzyme

Jest + Enzyme: How to test an image src?


I have a Logo component:

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;

Test file:

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

But when I run the test, there is some weird error:

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

How am I supposed to test that the image src === "assets/images/logo.png"?


Solution

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