sinon stub not replacing function

我是研究僧i 提交于 2019-12-23 09:31:31

问题


I'm trying to use sinon stub to replace a function that might take along time. But when I run the tests, the test code doesn't seem to be using the sinon stubs.

Here is the code I'm trying to test.

function takeTooLong() {
    return  returnSomething();
}

function returnSomething() {
    return new Promise((resolve) => {
        setTimeout(() => {
          resolve('ok')
        }, 1500)
    })
}

module.exports = {
  takeTooLong,
  returnSomething
}

and this is the test code.

const chai = require('chai')
chai.use(require('chai-string'))
chai.use(require('chai-as-promised'))
const expect = chai.expect
chai.should()
const db = require('./database')
const sinon = require('sinon')
require('sinon-as-promised')

describe('Mock the DB connection', function () {

it('should use stubs for db connection for takeTooLong', function (done) {

    const stubbed = sinon.stub(db, 'returnSomething').returns(new Promise((res) => res('kk')));
    const result = db.takeTooLong()

    result.then((res) => {

        expect(res).to.equal('kk')
        sinon.assert.calledOnce(stubbed);
        stubbed.restore()
        done()
    }).catch((err) => done(err))

})

I get an assertion error

 AssertionError: expected 'ok' to equal 'kk'
      + expected - actual

  -ok
  +kk

What am I doing wrong? Why isn't the stub being used ? The test framework in Mocha.


回答1:


Sinon stubs the property of the object, not the function itself.

In your case you are exporting that function within an object.

module.exports = {
  takeTooLong,
  returnSomething
}

So in order to properly call the function from the object, you need to replace your function call with the reference to the export object like :

function takeTooLong() {
    return module.exports.returnSomething();
}

Of course based on your code, you can always refactor it :

var exports = module.exports = {

    takeTooLong: function() { return exports.returnSomething() }

    returnSomething: function() { /* .. */ }

}


来源:https://stackoverflow.com/questions/40805349/sinon-stub-not-replacing-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!