【问题标题】:Jest unit test - mock value of async function within async function开玩笑的单元测试 - 异步函数中异步函数的模拟值
【发布时间】:2020-04-06 21:42:05
【问题描述】:

在我的 React 项目中,我正在对调用另一个异步函数的异步函数进行单元测试。

//SomeComponent.js
getAllJobs = async () => {
    var allJobStatuses = new Array();
    for(var endpointForRegion in this.props.regionalEndpointsMap) {
        let jobStatusesForRegion = await getJobStatuses(endpoint);
        allJobStatuses = allJobStatuses.concat(jobStatusesForRegion);
....
    }
    return allJobStatuses;
}

getJobStatuses = async (endpoint) => {
   const response = await fetch(endpoint, {
   ......
   return await response.json();
}
//SomeComponentTest.js
describe('<SomeComponent />', () => {
    ....
    beforeEach(() => {
        props = {regionalEndpointsMap: {
             'region1': 'region1ep',
             'region2': 'region2ep'
        }};
        wrapper = shallow(<SomeComponent {...props} />);
    });
    it('should get jobs for all regions', async () => {
        var startTime = new Date();
        let mockdata = {[
            {
            jobId: 'id',
            }
        ]};

        jest.spyOn(wrapper.instance(), 'getJobStatuses').mockResolvedValue(data);
        let allJobs = wrapper.instance.getAllJobs();
        let expectedData = [
            {jobId:'id'},
            {jobId:'id'}
        ];
        expect(allJobs).toEqual(expectedData);
}

虽然每次测试时,结果都只是一个空的 Promise {} 而不是 expectedData。 我已经尝试了许多我在网上找到的实现来模拟异步'getJobStatuses'函数的结果但没有运气(显示我从here使用的实现。模拟这个函数的结果的正确方法是什么,用于测试调用它的函数 (getAllJobs)

【问题讨论】:

    标签: javascript reactjs unit-testing asynchronous jestjs


    【解决方案1】:

    由于getAllJobsasync,它将返回一个承诺。你的意思是await这里的承诺吗?

    let allJobs = await wrapper.instance.getAllJobs();
    

    【讨论】:

    • 任何可以让它返回预期值的东西(抱歉,在一般情况下,在 JS 中使用 async/await 仍然是新的反应和绿色)。当我将 await 添加到 getAllJobs 的包装调用时,我奇怪地收到了 ReferenceError: getJobStatuses is not defined 错误
    猜你喜欢
    • 2021-10-12
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2020-03-11
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多