如何对异步函数进行正确的单元测试?

我有一个检查 url 地址的函数,如果该地址有效或无效,则返回 true。我需要使用 Jest 编写测试。为了完成这个任务,我编写了位于文档底部的测试用例。起初它引发了再生器运行时错误,但我通过相应的导入修复了该错误。但随后它开始抛出该错误。为了解决这个问题,我尝试导入 fetch 库,但错误没有解决。尽管我的应用程序中的错误功能正常工作。如何修复该错误?


ReferenceError:未定义提取


const fetch = require('node-fetch');

test("Testing valid product", async ()=>{

    const result = await valid('#products/1');

    expect(result).toBe(true);

});

我的功能


//FUNCTION WITH VALIDATION

export async function valid(path){

    //GETTING GROUP OF THE PRODUCTS

    let group = path.substr(path.indexOf('#')+1,path.indexOf('/')-1);

    //GET ID OF ITEM OF THE GROUP

    let url = path.substr(path.indexOf('/')+1);

    if(group=='products'){

        //CHECKING IF ITEM WITH THAT ID EXISTS

        let items = await fetch('https://my-json-server.typicode.com/ValeryDrozd/Valerydrozd.github.io/products').then(res => res.json());

        for(let i=0;i<items.length;i++){

            if(String(items[i]['id'])==url)return true;

        }

        return false;

    }

    if(group=='promos'){

        let items = await fetch('https://my-json-server.typicode.com/ValeryDrozd/Valerydrozd.github.io/promos').then(res => res.json());

        for(let i=0;i<items.length;i++){

            if(String(items[i]['id'])==url)return true;

        }

        return false;

    }

    if(group=='order'){

        let orders = JSON.parse(localStorage.getItem('orders'));

        if(orders==null)return false;

        if(orders['orderids'].indexOf(url)==-1)return false;

        return true;

    }

    return false;

}

我的 jest.config.js 文件


module.exports = {

    collectCoverage: true,

    transform: { '\\.js$': 'babel-jest', },

};


慕桂英4014372
浏览 57回答 1
1回答

LEATH

我认为您可以在测试之前通过使用或自己jest-fetch-mock创建模拟来解决此问题,如下所示:fetch// Mock at global levelglobal.fetch = jest.fn(() =>&nbsp; Promise.resolve({&nbsp; &nbsp; json: () => Promise.resolve({/* whatever you want to ressolve */}),&nbsp; }));test("Testing valid product", async ()=>{&nbsp; const result = await valid('#products/1');&nbsp; expect(result).toBe(true);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript