Warm tip: This article is reproduced from stackoverflow.com, please click
javascript jestjs mocking node.js testing

Node Jest mocking a function in a function

发布于 2020-04-10 16:16:18

I am Testing a method like such:

test('Test', async () => {
    const result = await methodBeingTested(someData);
    })
})

Then the method I am testing looks something like this:

import { insertData } from '../util/api';
export async function methodBeingTested(someData: any) {
    const data = await insertData(dateIdsomeData)

    //Do Some other stuff
    return data
}

I would like to mock the data insertData method returns just so it doesn't do the axios request or the insert into mongo / sql.

How am I able to do this with Jest? I am mainly just wanting to test the functionality of the other stuff going on in the methodBeingTested.

Thanks

Questioner
twcardenas
Viewed
62
Kaca992 2020-02-02 05:22

Do this:

jest.mock('../util/api', () => ({
   insertData: () => Promise.resolve(mockResult) // put here some result 
}));

// your tests

Just make sure that your path is correct.