Draq
Draq

Reputation: 11

unit test, Sinon js spies

So i have this little function

module.exports = {
  setupNewUser(info, callback) {
    var user = {
      name: info.name,
      nameLowercase: info.name.toLowerCase()
    }

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

and im using sinon to test this method

const setupNewUser = require('./index').setupNewUser
const sinon = require('sinon')
const assert = require('assert')

const Database = {
  save(info, cb) {
    if (info === undefined) {
      return cb('nope')
    } else {
      return cb()
    }
  }
}

describe('#save()', function () {
  it('should call save once', function() {
    var save = sinon.spy(Database, 'save')

    setupNewUser({ name: 'test' }, function() { })

    save.restore()
    sinon.assert.calledOnce(save)
  })
})

When i ran the test it fail any knows why ?

Error message

AssertError: expected save to be called once but was called 0 times

Upvotes: 1

Views: 726

Answers (1)

wmock
wmock

Reputation: 5492

I believe the reason this is happening is because you're not actually stubbing out the method you think you are. In your test code, your intention was to create a fake Database object so that your actual source code will call this object's method. What you need to stub out is that actual Database object that your source code uses.

Normally in your source code, you'd probably import the Database object. You'll need to import the same Database object and stub it out in your test code as well.

Upvotes: 2

Related Questions