mercredi 1 juillet 2020

How to use jest to test a function's return value(array)?

Here is my function to recursively loop through a object:


const helper = (obj,list) =>{
    for (var property in obj){
        if(obj.hasOwnProperty(property)) {
            if(typeof obj[property] == "object") {     
                helper(obj[property],list);
            }else {
                if (property === "$ref"){
                    if(!list.includes(obj[property])){
                        list.push(obj[property]);
                    }
                }
            }
        }
    }
    return list;
};

To run the code, just do helper(some_obj,[])

Here is my jest test code:

describe('helper function test',  () =>{
    it('should return a list', () =>{
        const mock = jest.fn((obj,[]) => helper(obj,[]));
        const list = mock(obj,[]);
        expect(list).toMatch(['something']);
    });
});

I have also tried:

describe('helper function test',  () =>{
    it('should return a list', () =>{
        const list = helper(obj, []);
        expect(list).toMatch(['something']);
    });
});

The jest tells me the expect object is a array but it's value is [], which means empty. Actually I did a manually test for helper function in the function file, the return has no problem, which is what I expect.

One thing to mention, I use this helper inside of a promise later, I do not know the issue is related to promise, since the promise function has not called. I even tried to comment out the promise function, still no luck.

Would someone tells me how to get the real result from the jest? I would really appreciate any helps here! Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire