javascript 如何使用sinon来模拟函数中的函数?

qoefvg9y  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(111)

yellow.js

async function yellow(
  prop1,
  prop2
) {
  //does stuff and returns an array
  return [1, 2, 3]
}

blue.js

const Yellow = require('./yellow')

async function blue(
  prop1,
  prop2
) {
 
      const getIds = await Yellow(
        prop1,
        prop2
      )

      //Do stuff and return an array

  return [1, 2, 3]
}

blue.test.js

it('should return an array of ids', async () => {
      await blue(
        1,
        2
      )
    })

当我尝试使用sinon对blue进行单元测试时,我如何使用stub yellow?
我知道可以stub对象的属性,如sinon.stub(Yellow,'yellow'),但在本例中,它抛出了一个错误

xoefb8l8

xoefb8l81#

不清楚您是否指示stub解决问题中黄色的异步调用,但如果您遵循以下步骤,它应该会工作。

const Yellow = require('Yellow');

const Sinon = require('Sinon');

const yellowStub = Sinon.stub(Yellow, 'yellow');

it('should return an array of ids', async () => {
      yellowStub.resolves([1,2,3]);

      await blue(1,2)
    })

第二:在blue.js中导入Yellow之后,需要调用函数yellow。

const Yellow = require('./yellow')

    async function blue(prop1, prop2) {
      const getIds = await Yellow.yellow(prop1, prop2)

      //Do stuff and return an array

      return getIds
    }

第三:需要导出黄色函数

async function yellow(prop1, prop2 ) {
  //does stuff and returns an array
  return [1, 2, 3]
}

module.exports = { yellow }
qojgxg4l

qojgxg4l2#

不需要使用sinon,可以使用jest.https://jestjs.io/docs/mock-functions自带的mock函数

相关问题