如何使用Jest / Enzyme测试图像的硬编码onError属性?

时间:2019-07-09 20:23:53

标签: reactjs jestjs enzyme

我有以下代码:

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

那是我组件的最简单版本,只是为了让你们知道。我想使用Jest和Enzyme测试此onError,但由于它不是道具的一部分,因此我无法找到一种模拟它的方法。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案:

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

覆盖率100%的单元测试结果:

 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

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56960035