我有一個(gè)檢查 url 地址的函數(shù),如果該地址有效或無效,則返回 true。我需要使用 Jest 編寫測(cè)試。為了完成這個(gè)任務(wù),我編寫了位于文檔底部的測(cè)試用例。起初它引發(fā)了再生器運(yùn)行時(shí)錯(cuò)誤,但我通過相應(yīng)的導(dǎo)入修復(fù)了該錯(cuò)誤。但隨后它開始拋出該錯(cuò)誤。為了解決這個(gè)問題,我嘗試導(dǎo)入 fetch 庫,但錯(cuò)誤沒有解決。盡管我的應(yīng)用程序中的錯(cuò)誤功能正常工作。如何修復(fù)該錯(cuò)誤?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', },};
如何對(duì)異步函數(shù)進(jìn)行正確的單元測(cè)試?
慕桂英4014372
2023-11-12 15:24:10