繁体   English   中英

sinon存根不替换功能

[英]sinon stub not replacing function

我正在尝试使用 sinon 存根来替换可能需要很长时间的函数。 但是当我运行测试时,测试代码似乎没有使用 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

我做错了什么? 为什么不使用存根? Mocha 中的测试框架。

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

在您的情况下,您是在对象中导出该函数。

module.exports = {
  takeTooLong,
  returnSomething
}

因此,为了从对象正确调用函数,您需要将函数调用替换为对导出对象的引用,例如:

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

当然,根据您的代码,您可以随时重构它:

var exports = module.exports = {

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

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

}

您可能想查看 Proxyquire 以存根/监视直接导出的函数。 https://www.npmjs.com/package/proxyquire/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM