2016-11-25 75 views
1

我想用sinon存根替换一个可能需要时间的函数。但是当我运行测试时,测试代码似乎没有使用sinon stub。sinon存根没有替代函数

这是我试图测试的代码。

function takeTooLong() { 
    return returnSomething(); 
} 

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

module.exports = { 
    takeTooLong, 
    returnSomething 
} 

这是测试代码。

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)) 

}) 

我得到断言错误

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

    -ok 
    +kk 

我在做什么错?为什么不使用存根?摩卡的测试框架。

+0

你可以在你正在测试的代码和测试代码中添加'export'和'require'方法吗? – drinchev

回答

5

Sinon将对象的property存根,而不是函数本身。

在你的情况下,你是在一个对象内导出该函数。

module.exports = { 
    takeTooLong, 
    returnSomething 
} 

所以,为了正确地从对象调用函数,你需要与参考像出口对象来代替你的函数调用:

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

当然根据你的代码,你总是可以重构它:

var exports = module.exports = { 

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

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

}