TransWikia.com

How to make proper unit test of async function?

Stack Overflow Asked by Pavlo on January 30, 2021

I have a function which checks url address and returns true if that address is valid or no.
I need to write tests to that using Jest. To complete this task I wrote testcase which located in the bottom of the document. At first it threw regenerator-runtime error, but I fixed that with according import. But then it started to throw that error. To fix it, I tried to import fetch library, but error didn’t solved. Despite that error function in my app working normally. How to fix that error?

ReferenceError: fetch is not defined

const fetch = require('node-fetch');
test("Testing valid product", async ()=>{
    const result = await valid('#products/1');
    expect(result).toBe(true);
});

My function

//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;
}

My jest.config.js file

module.exports = {
    collectCoverage: true,
    transform: { '\.js$': 'babel-jest', },
};

One Answer

I think you could resolve this issue by either using jest-fetch-mock or create a mock fetch on your own before your test as following:

// 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);
});

Answered by tmhao2005 on January 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP