【问题标题】:Node Jest mocking a function in a functionNode Jest 在函数中模拟函数
【发布时间】:2020-02-01 21:18:35
【问题描述】:

我正在测试这样的方法:

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

那么我正在测试的方法看起来是这样的:

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

    //Do Some other stuff
    return data
}

我想模拟 insertData 方法返回的数据,这样它就不会执行 axios 请求或插入到 mongo/sql 中。

我怎么能用 Jest 做到这一点?我主要只是想测试methodBeingTested 中其他东西的功能。

谢谢

【问题讨论】:

    标签: javascript node.js testing mocking jestjs


    【解决方案1】:

    这样做:

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

    只要确保你的路径是正确的。

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2022-06-29
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      相关资源
      最近更新 更多