如何断言一个函数被多个参数调用

时间:2018-08-12 16:33:34

标签: javascript unit-testing mocha sinon

我正在用一个简单的例子学习双重测试:

const Database = require('./Database')

const setupNewUser = (info, callback) => {
    const user = {
        name: info.name,
        nameLowercase: info.name.toLowerCase()
    }

    try {
        Database.save(user, callback)
    } catch (err) {
        callback(err)
    }
}

module.exports = setupNewUser

我有一个带有对象和回调的函数:

const Database = {
    save: (user, callback) => {
        callback(user)
    }
}
module.exports = Database

如何测试对象save是否同时被调用和回调。以下是我正在尝试的:

it('it calls Database.save with a callback', () => {
    const saveSpy = sinon.spy(Database, 'save')
    const arg = {
        name: info.name,
        nameLowercase: info.name.toLowerCase()
    }
    setupNewUser(info, function() {})

    //I'm able to assert that save is called with arg sinon.assert.calledWith(saveSpy, arg)
    sinon.assert.calledWith(saveSpy, arg, function() {}) //This is failing
})

1 个答案:

答案 0 :(得分:0)

您应该.stub.spy进行API调用。我还建议您使用sinon.sandbox,以便易于管理测试清理。阅读有关here

describe('Setup new user', function() {
  const sandbox = sinon.createSandbox();

  afterEach(function() {
    sandbox.restore();
  });

  it('should call Database.save with a callback', function(){
    const databaseSaveStub = sandbox.stub(Database, 'save');

    const user = {
      name: 'Some Name',
      nameLowercase: 'some name'
    };

    const callbackFn = sandbox.spy();

    setupNewUser(user, callbackFn);

    sinon.assert.calledOnce(Database.save);        
    sinon.assert.calledWith(databaseSaveStub, user, callbackFn);
  });
});