Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 395
bigpotato Avatar asked Jan 12 '18 19:01

bigpotato


3 Answers

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

     });
 });
like image 108
thierno Avatar answered Nov 11 '22 23:11

thierno


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

like image 33
skyboyer Avatar answered Nov 12 '22 00:11

skyboyer


/* **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);
  });
});
like image 2
Pooja Gupta Avatar answered Nov 11 '22 23:11

Pooja Gupta