首页 > 解决方案 > 如何断言 sinon mongoose 存根

问题描述

拥有一个使用 mongoose 模型的单元测试用例,我需要确保调用了 authModel.create。如何断言?

我的单元测试:

     const createUserStub = sinon.stub(authModel, 'create')
            .resolves(userContent)

        return request(app).post('/auth/create')
            .send(userContent)
            .set('Accept', 'application/json')
            .expect((response) => {
                const apiResponse = JSON.parse(response.text)

                expect(createUserStub.calledOnce).to.equal(true)
                expect(apiResponse).to.be.an('Object')
                expect(apiResponse).to.have.property('_id')
                expect(apiResponse).to.have.property('name')
                expect(apiResponse).to.have.property('last_name')
                expect(response.res.statusCode).to.equal(200)
            }).end(done)

在第一个期望断言总是返回 false。

标签: javascriptsinon

解决方案


您需要检查被调用的属性而不是 calledOnce ( calledOnce 是 sinon.spy 的属性)。

expect(createUserStub.called).to.equal(true)

应该有效。谢谢!


推荐阅读