简体   繁体   English

Node Jest 在函数中模拟函数

[英]Node Jest mocking a function in a function

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.我想模拟数据insertData方法返回,这样它就不会执行 axios 请求或插入到 mongo/sql 中。

How am I able to do this with Jest?我怎样才能用 Jest 做到这一点? I am mainly just wanting to test the functionality of the other stuff going on in the methodBeingTested .我主要只是想测试methodBeingTested其他内容的功能。

Thanks谢谢

Do this:做这个:

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

// your tests

Just make sure that your path is correct.只要确保你的路径是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM