首页 > 解决方案 > 如何让附加到全局的属性与 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 模型)。

我敢肯定这是非常明显的事情,所以任何指针都将不胜感激。谢谢。

标签: javascriptmocha.jssequelize.jssinonstub

解决方案


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

以下应该工作

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

您还可以创建存根实例:

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

推荐阅读