我怎样才能让一个 属性 附加到全局以正确地与 sinon 存根?

How can I get a property attached to a global to stub properly with sinon?

我有一个 helper.js 在我的测试之前加载:

before(async function() {
    this.timeout(30000)
    global.db = require(`${process.cwd()}/models`)()
    ...

然后在我的测试中,我有:

describe.only('Phone Library', () => {
    let updateCallSpy
    beforeEach(() => {
        sinon.stub(twilioClient.calls, 'create').resolves({})
        updateCallSpy = sinon.stub(global.db.models.Call, 'update').resolves(true)
            // sinon.stub(global.db.models.Conversation, 'update').resolves({})
    })

twilioClient.calls.create 存根正确。但是 global.db.models.Call.update 没有。

在我的实际代码中,我是这样使用它的:

        await global.db.models.Call.update({ status: newCallStatus }, { where: { id: foundConversation.Call.id } })

当我console.log(global.db.models.Call)时,它只是输出Call。但是,.update 函数在那里并执行它应该执行的操作(更新的 Sequelize 模型)。

我敢肯定这是非常明显的事情,因此将不胜感激任何指点。谢谢。

sequelize 模型方法由 sequelize 核心定义为 prototype

以下应该有效

updateCallSpy = sinon.stub(global.db.models.Call.prototype, 'update').resolves(true)

您还可以创建存根实例:

updateCallStubInstance = sinon.createStubInstance(global.db.models.Call)