javascript - 如何在 React 和 Jest 中对 promise 拒绝进行单元测试

标签 javascript reactjs unit-testing jestjs es6-promise

我正在尝试为 React 组件编写单元测试。这是一个相当标准的组件,它调用 promise 返回方法并使用“then”和“catch”来处理解决方案。我的测试试图验证它在 promise 被拒绝时调用了正确的方法,但是尽管遵循了我认为是标准的模式,但我无法开 Jest 来验证调用。我在这里列出了相关文件,还提供了一个 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;

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

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

export default { getList };

这是测试用例:

import ListComponent from './ListComponent';
import api from '../api//ListApi';

describe('ListComponent > fetchList() > When the call to getList fails', () => {
    it('Should call fetchListFailed with the error', async () => {

        expect.hasAssertions();

        //Arrange
        const error = { message: "some error" };
        const errorResponse = () => Promise.reject(error);
        const componentInstance = new ListComponent();

        api.getList = jest.fn(() => errorResponse());
        componentInstance.fetchListFailed = jest.fn(() => { });

        //Act
        componentInstance.fetchList();

        //Assert
        try {
            await errorResponse;
        } catch (er) {
            expect(componentInstance.fetchListFailed).toHaveBeenCalledWith(error);
        }

    });
});

问题是测试没有执行 catch block ,因此,在这种情况下,expect.hasAssertions() 没有通过测试。谁能帮我理解 catch block 没有执行?在 try block 中包装 await 并在 catch 中断言似乎是 docs 中的标准模式但我对 Js 和 React 还很陌生,显然做错了什么。

这是 sample project在 GitHub 上。任何帮助将不胜感激 =)

最佳答案

在您的控制台中:

const errorResponse = () => Promise.reject();
await errorResponse;
//() => Promise.reject()

您正在等待一个函数,而不是调用该函数的结果。你想:

await errorResponse();

编辑:

除此之外,测试的其余部分令人困惑。我相信您实际上想测试调用组件的 fetchList 方法时会发生什么,但我假设它失败了。所以你需要在你的测试中调用它,并等待它的响应:

  1. 更新组件的 fetchList 方法以返回 promise 。
  2. await componentInstance.fetchList() 而不是 await errorResponse()
  3. 因为您catch fetchList 中的错误,所以您永远不会输入catchtry...catch 所以你的最终测试应该是这样的:

测试:

//Arrange
const error = { message: "some error" };
const errorResponse = () => Promise.reject(error);
const componentInstance = new ListComponent();

api.getList = jest.fn(() => errorResponse());
componentInstance.fetchListFailed = jest.fn(() => { });

//Act
await componentInstance.fetchList();
expect(componentInstance.fetchListFailed).toHaveBeenCalledWith(error);

组件:

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

关于javascript - 如何在 React 和 Jest 中对 promise 拒绝进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187245/

相关文章:

android - 如何将数据库测试夹具从我的单元测试应用程序传输到设备

c# - 运行测试时 HttpResponseBase.Headers 为空

java - 从 http ://www. autorenlexikon.lu 接收 JSON 列表

Javascript 验证函数值

javascript - Redux- 表单 : get and show all values of a wizard form before submit

javascript - 在不使用扩展运算符的情况下正确更新 React.js 状态中的对象

unit-testing - AutoFixture生成JsonDocument?

javascript - Typescript 是否仅包含已批准的 ECMAScript 功能?

javascript - 如何记录 NodeJS/Express 上的所有传出请求?

javascript - 在服务器端呈现的 Express/React 应用程序上使用 passport-jwt