How to test logo image in ReactJS application using Enzyme and Jest?

Writing test cases using Enzyme and Jest in ReactJS application is very convenient. The rapid growth of ReactJS allows Enzyme and Jest to be a popular testing tool in front-end web development.

In this article, we will try to cover a basic unit test case using Enzyme and Jest. Let’s consider we have a logo image and we want to test the logo image source attribute.

We are assuming that your application has a proper setup of Enzyme and Jest. If the Enzyme and Jest are not configured correctly, you can read this article.

Image attribute exists unit test is really basic but it is always handy to know the entire flow for a beginner. In this test, we are going to use a mount method from Enzyme. We could do the same using a shallow method. Following is the code segment:

The component: App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

The test case: App.test.js

import React from 'react';
import { mount } from 'enzyme';
import App from './App';



describe('Application home page test cases', () => {
  it('Logo image source attribute should have value', () => {
    const headerPage = mount();
    expect(headerPage.find('img').prop('src')).toBeTruthy();
  });
});

How to run the test?

$ yarn test 
or
$ npm test

The output:

 PASS  src/App.test.js
  Application home page test cases
    ✓ Logo image source attribute should have value (43ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.812s, estimated 3s
Ran all test suites.

Watch Usage: Press w to show more.

https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/mount.html

Share