Luis Felipe Perez
Luis Felipe Perez

Reputation: 349

How to test hard coded onError attribute for image using Jest/Enzyme?

I have the following code:

const Avatar = ({imageSrc, imageAlt, imageWidth, imageHeight}) => (
<img
  src={imageSrc}
  alt={imageAlt}
  style={{ width: imageWidth, height: imageHeight }}
  onError={e => {
    e.target.src = '/static/images/placeholder/avatar.png';
  }}
/>)

That's is the simplest version of my component, just to let you guys aware of that. I want to test this onError using Jest and Enzyme but I couldn't find a way to mock it since it doesn't come as part of props.

How do I do that?

Upvotes: 0

Views: 1070

Answers (1)

Lin Du
Lin Du

Reputation: 102597

Here is an unit test solution:

index.ts:

import React from 'react';

export const Avatar = ({ imageSrc, imageAlt, imageWidth, imageHeight }) => (
  <img
    src={imageSrc}
    alt={imageAlt}
    style={{ width: imageWidth, height: imageHeight }}
    onError={e => {
      // @ts-ignore
      e.target.src = '/static/images/placeholder/avatar.png';
    }}
  />
);

index.spec.ts:

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

describe('Avatar', () => {
  it('should handle error', () => {
    const mProps = {
      imageSrc: 'http://123.com/avatar.png',
      imageAlt: 'alt',
      imageWidth: 123,
      imageHeight: 456
    };
    const wrapper = mount(<Avatar {...mProps}></Avatar>);
    expect(wrapper.find('img').props()).toEqual({
      src: mProps.imageSrc,
      alt: mProps.imageAlt,
      style: { width: mProps.imageWidth, height: mProps.imageHeight },
      onError: expect.any(Function)
    });
    expect((wrapper.getDOMNode() as HTMLImageElement).src).toBe(mProps.imageSrc);
    const mEvent = { target: wrapper.getDOMNode() } as any;
    wrapper.find('img').prop('onError')!(mEvent);
    expect(mEvent.target.src).toBe('http://localhost/static/images/placeholder/avatar.png');
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/56960035/index.spec.tsx
  Avatar
    ✓ should handle error (47ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.385s, estimated 8s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56960035

Upvotes: 1

Related Questions