嘲笑在then()内部调用的函数

时间:2020-03-12 12:46:57

标签: javascript reactjs asynchronous testing jestjs

我正在尝试测试此功能

const handleSave = () => {
    const cveIds = cveList.map(item => item.id);
    return setCveStatus({
        status_id: parseInt(statusId),
        cve: cveIds,
        status_text: justification
    })
    .then(() => !checkboxState && setSystemCveStatus({ cve: cveIds }))
    .then(updateRef);
};

调用了我正在嘲笑的两个函数 setCveStatus setSystemCveStatus

const setCveStatusMock = jest.fn(parameters => new Promise(resolve => resolve(parameters)));
const setSystemCveStatusMock = jest.fn(parameters => new Promise(resolve => resolve(parameters)));

deps.setCveStatus = setCveStatusMock;
deps.setSystemCveStatus = setSystemCveStatusMock;

并测试他们的名字

expect(setCveStatusMock).toBeCalledWith({
    status_id: 3,
    status_text: 'new',
    cve: ['CVE-2020-0001']
});

expect(setSystemCveStatusMock).toBeCalledWith({
    cve: ['CVE-2020-0001']
});

但是第二个期望失败了,即使它本来不应该有。 如何模拟和测试.then()内部调用的函数?

1 个答案:

答案 0 :(得分:1)

一种优雅解决此问题的方法是使用asyncFn

用它代替:

const setCveStatusMock = jest.fn(parameters => new Promise(resolve => resolve(parameters)));

// ...

expect(setSystemCveStatusMock).toBeCalledWith({
    cve: ['CVE-2020-0001']
});

可以

import asyncFn from '@asyncFn/jest';
const setCveStatusMock = asyncFn();

// ...

// Resolve the call for setCveStatusMock and await for anything that happens as a result of that.
await setCveStatusMock.resolve();

// ...

expect(setSystemCveStatusMock).toBeCalledWith({
    cve: ['CVE-2020-0001']
});

免责声明:我是作者之一。