Jest - 如何模拟在测试函数中调用的函数

时间:2021-06-07 16:35:00

标签: javascript node.js unit-testing testing jestjs

我有包含多个函数(foobar 等)的模块。

// moduleA.js

const someModule = require('someModule')


const moduleA = () => {
   const bar = (param1, param2) => {
     // some implementation
   }

   const foo = (params) => {
    // some implementation
    bar(1, 2)
   }

   return Object.assign({}, someModule, {
      foo,
      bar
   })
}

module.exports = moduleA

我想要做的是模拟在我当前的测试 (bar) 函数中调用的其他模块函数 (foo)。

// jest test file
describe('Testing foo, mocking bar', () => {
    const checker = moduleA()

    it.only('When this, then that', async () => {
        // THIS IS NOT WORKING
        const spy = jest.spyOn(checker, "bar").mockReturnValue("XXXX")


        const response = await checker.foo({ 1, 2, 3})
        expect(response).toBeDefined()
    })
})

监视或存根 bar 函数以便我可以模拟结果并只专注于测试 foo 功能的正确方法是什么?

0 个答案:

没有答案