为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英4014372 2023-11-12 15:24:10
我有一个检查 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 VALIDATIONexport 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', },};
查看完整描述

1 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

我认为您可以在测试之前通过使用或自己jest-fetch-mock创建模拟来解决此问题,如下所示:fetch


// Mock at global level

global.fetch = jest.fn(() =>

  Promise.resolve({

    json: () => Promise.resolve({/* whatever you want to ressolve */}),

  })

);


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

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

  expect(result).toBe(true);

});


查看完整回答
反对 回复 2023-11-12
  • 1 回答
  • 0 关注
  • 52 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信