Sinon称为With和calledWithMatch失败的对象编辑:Sinon间谍对象的构造函数

我是unit testing新手,正在使用Mocha,Sinon和Chai来testingNodeJs代码。 问题是我对stub.calledWith()的期望总是失败,即使testing错误显示了两个在语法上相同的对象。

我使用Sinon来存储一个mongoose模型的保存方法,并检查这个存根被调用了正确的细节。

我正在testing的function:

async function createGroup(details) { 'use strict'; Logger.info(`create group called`); const group = new UserGroup(this.formatGroup(details)); const result = await group.save(); Logger.verbose(`results of save: ${JSON.stringify(result)}`); return result; } 

unit testing

 describe('object creation', function () { 'use strict'; const saveStub = sinon.stub(UserGroup.prototype, 'save'); mongoose.Promise = Promise; beforeEach(function (done) { saveStub.reset(); return done(); }); after(function (done) { saveStub.restore(); return done(); }); it('creates an object without error', async function () { const correctDetailsIn = { name: 'stark', foo: 'bar', bar: 'baz', users: [{ email: 'eddard@stark.com', firstName: 'eddard', surname: 'stark' }] }; const persistableDetails = { name: 'stark', users: [{ email: 'eddard@stark.com', firstName: 'eddard', surname: 'stark' }] }; const expectedDetailsOut = { _id: 'someidhere', name: 'stark', users: [{ email: 'eddard@stark.com', firstName: 'eddard', surname: 'stark' }] }; saveStub.resolves(expectedDetailsOut); const res = await userGroupService.createGroup(correctDetailsIn); expect(res).to.equal(expectedDetailsOut); //I tried the four variations below. expect(saveStub).to.be.calledWithMatch(persistableDetails); //expect(saveStub).to.be.calledWith(persistableDetails); //sinon.assert.calledWithMatch(saveStub, persistableDetails) //sinon.assert.calledWith(saveStub, persistableDetails) }) }) 

我尝试过的四种方法都失败了,其中包括:

 AssertionError: expected save to have been called with arguments matching { name: "stark", users: [{ email: "eddard@stark.com", firstName: "eddard", surname: "stark" }] } { name: "stark", users: [{ email: "eddard@stark.com", firstName: "eddard", surname: "stark" }] } 

我觉得我错过了一些简单的工作。

编辑:

所以这是简单的(当然,我错过了) Model.save()是一个实例方法,所以它被称为不带参数。 这与西恩认为两次展现期望的东西有关,而不是期望和现实。

我真正需要做的是弄清楚如何在Model构造函数上存根/窥探,以确保使用正确的参数调用它。 如果有人知道如何做到这一点,我可以真正做到这一点。