相关疑难解决方法(0)

如何在Redux动作(或该动作中分配的其他回调)的上下文中使用Jest测试`image.onload`

我的问题是我试图对某个功能进行单元测试,但无法弄清楚如何测试其中的一部分。

这是一个react / redux操作,它执行以下操作:

1)使用图像网址检索json数据

2)将图像加载到Image实例中,并将其大小分派给reducer(使用Image.onload加载图像时异步)

3)派遣完成到减速机的提取

图片加载是异步发生的,因此当我尝试进行单元测试时,它不会被调用。而且,我不能只是模拟一下,因为图像实例是在函数内创建的。

这是我要测试的代码(删除了一些检查,分支逻辑和内容):

export function fetchInsuranceCardPhoto() {
    return dispatch => {
        dispatch(requestingInsuranceCardPhoto());
        return fetch(`${api}`,
            {
                headers: {},
                credentials: 'same-origin',
                method: 'GET',
            })
            .then(response => {
                switch (response.status) {
                    case 200:
                        return response.json()
                            .then(json => {
                                dispatch(receivedInsuranceCardPhoto(json));
                            })
                }
            });
    };
}

function receivedInsuranceCardPhoto(json) {
    return dispatch => {
        const insuranceCardFrontImg = json.insuranceCardData.url_front;
        const insuranceCardBackImg = json.insuranceCardData.url_back;

        if (insuranceCardFrontImg) {
            dispatch(storeImageSize(insuranceCardFrontImg, 'insuranceCardFront'));
        }

        return dispatch(receivedInsuranceCardPhotoSuccess(json));
    };
}

function receivedInsuranceCardPhotoSuccess(json) {
    const insuranceCardFrontImg = json.insuranceCardData.url_front;
    const …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jest react-redux

4
推荐指数
1
解决办法
4157
查看次数

你如何使用Jest来测试img.onerror

我创建了一个React组件,用于加载图像并确定图像是否成功加载.

import React from 'react';
import PropTypes from 'prop-types';
import { LOADING, SUCCESS, ERROR } from '../helpers';

class Image extends React.Component {
  static propTypes = {
    onError: PropTypes.func,
    onLoad: PropTypes.func,
    src: PropTypes.string.isRequired,
  }

  static defaultProps = {
    onError: null,
    onLoad: null,
  }

  constructor(props) {
    super(props);
    this.state = { imageStatus: LOADING };
    this.initImage();
  }

  componentDidMount() {
    this.image.onload = this.handleImageLoad;
    this.image.onerror = this.handleImageError;
    this.image.src = this.props.src;
  }

  initImage() {
    this.image = document.createElement('img');
    this.handleImageLoad = this.handleImageLoad.bind(this);
    this.handleImageError = this.handleImageError.bind(this);
  }

  handleImageLoad(ev) {
    this.setState({ …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme

3
推荐指数
3
解决办法
5063
查看次数

标签 统计

unit-testing ×2

enzyme ×1

javascript ×1

jest ×1

jestjs ×1

react-redux ×1

reactjs ×1