小编Dav*_*Nee的帖子

如何在 React 和 Jest 中单元测试承诺拒绝

我正在尝试为反应组件编写单元测试。这是一个相当标准的组件,它调用一个 promise 返回方法并使用“then”和“catch”来处理解析。我的测试试图验证当承诺被拒绝时它调用了正确的方法,但是尽管遵循我认为的标准模式,但我无法开玩笑地验证调用。我在这里列出了相关文件,并且还提供了一个 github 示例,该示例链接在问题的底部。该示例只是一个使用 npx 创建的新 React 应用程序,并添加了以下文件。

这是我的示例组件:

import React from 'react';
import api from '../api/ListApi';

class ListComponent extends React.Component {

    constructor(props) {
        super(props);
        this.fetchListSuccess = this.fetchListSuccess.bind(this); 
        this.fetchListFailed = this.fetchListFailed.bind(this); 

    }

    fetchList() {
        api.getList()
        .then(this.fetchListSuccess)
        .catch(this.fetchListFailed);
    }

    fetchListSuccess(response) {
        console.log({response});
    };

    fetchListFailed(error) {
        console.log({error});
    };

    render() {
        return(<div>Some content</div>);
    };
}

export default ListComponent;
Run Code Online (Sandbox Code Playgroud)

这是 api 类(请注意,如果您运行该应用程序,则该 api 不存在,例如仅在此处):

const getList = () => fetch("http://someApiWhichDoesNotExist/GetList");

export default { getList };
Run Code Online (Sandbox Code Playgroud)

这是测试用例:

import ListComponent from './ListComponent';
import api from …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs es6-promise jestjs

2
推荐指数
1
解决办法
7240
查看次数

标签 统计

es6-promise ×1

javascript ×1

jestjs ×1

reactjs ×1

unit-testing ×1