【问题标题】:How to mock a chained function call in Sinon如何在 Sinon 中模拟链式函数调用
【发布时间】:2021-12-17 09:38:18
【问题描述】:

你如何使用这样的诗乃模拟?

const data = await getData(); 
const res= await data.collection('myCollection').deleteOne({ id: 12 });

【问题讨论】:

标签: unit-testing mocha.js sinon


【解决方案1】:

您可能正在寻找.returnsThis(),它只返回函数的this,就像这样的流式API 所做的那样,并且专门用于存根此类API。

你可以这样使用它:

const db = require('...')

async function test() {
  // Setup
  const fakeResponse = {
    collection: Sinon.stub().returnsThis(),
    deleteOne: Sinon.stub().returnsThis()
  }
  Sinon.stub(db, 'getData').resolves(fakeResponse)
  
  // Call your code that does stuff
  const data = await db.getData(); 
  const res = await data.collection('myCollection').deleteOne({ id: 12 })
  
  // Assert
  Sinon.assert.calledWith(fakeResponse.collection, 'myCollection')
  Sinon.assert.calledWith(fakeResponse.deleteOne, { id: 12 })
}

我在这里假设getData 是某个对象的方法,比如db。如果没有,您将不得不想出其他方法来存根 getData()

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2013-08-11
    • 2017-07-23
    • 2019-12-15
    相关资源
    最近更新 更多