sinon存根不替换功能 [英] sinon stub not replacing function

查看:77
本文介绍了sinon存根不替换功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我要测试的代码。

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

})

我收到断言错误

I get an assertion error

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

  -ok
  +kk

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

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

推荐答案

Sinon存根属性对象,而不是函数本身。

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() { /* .. */ }

}

这篇关于sinon存根不替换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆