javascript - 如何检查在 Sinon 中是否使用正确的属性调用了类构造函数?

标签 javascript tdd sinon

我正在测试从外部库实例化对象的代码。为了使其可测试,我决定注入(inject)依赖项:

归结为:

const decorator = function (obj, _extLib) {
  var ExtLib = _extLib || require('extlib')
  config = determineConfig(obj) //This is the part that needs testing.
  var el = new ExtLib(obj.name, config)
  return {
    status: el.pay({ amt: "one million", to: "minime" })
    bar: obj.bar
  }
}

在我的测试中,我需要确定外部库是使用正确的 config 实例化的。我对这个外部库是否有效(有效)或调用它是否给出结果不感兴趣。为了这个例子,让我们假设在实例化时,它调用一个慢速银行 API,然后锁定数百万美元:我们希望它 stub 、模拟和监视。

在我的测试中:

it('instantiates extLib with proper bank_acct', (done) => {
  class FakeExtLib {
    constructor(config) {
      this.acct = config.bank_acct
    } 
    this.payMillions = function() { return }
  }

  var spy = sandbox.spy(FakeExtLib)
  decorator({}, spy) // or, maybe decorator({}, FakeExtLib)?
  sinon.assert.calledWithNew(spy, { bank_acct: "1337" })

  done()
})

请注意,是否进行测试,例如el.pay() 被调用,工作正常,使用 spy ,在 sinon 中。这是用 new 的实例化,这似乎无法测试。

为了调查,让我们让它更简单,内联测试所有内容,避免被测试的主题,decorator 函数完全:

it('instantiates inline ExtLib with proper bank_acct', (done) => {
  class ExtLib {
    constructor(config) {
      this.acct = config.bank_acct
    }
  }

  var spy = sandbox.spy(ExtLib)
  el = new ExtLib({ bank_acct: "1337" })
  expect(el.acct).to.equal("1337")
  sinon.assert.calledWithNew(spy, { bank_acct: "1337" })
  done()
})

expect 部分通过。所以显然它都被正确调用了。但是 sinon.assert 失败了。仍然。为什么?

我如何检查在 Sinon 中调用的类构造函数是否具有正确的属性?“calledWithNew 是否可以这样使用?我应该监视另一个函数,例如 ExtLib.prototype .constructor 代替?如果是,怎么做?

最佳答案

你真的很接近。

对于最简单的示例,您只需要使用 spy 而不是 ExtLib 创建 el:

it('instantiates inline ExtLib with proper bank_acct', (done) => {
  class ExtLib {
    constructor(config) {
      this.acct = config.bank_acct
    }
  }

  var spy = sandbox.spy(ExtLib)
  var el = new spy({ bank_acct: "1337" })  // use the spy as the constructor
  expect(el.acct).to.equal("1337")  // SUCCESS
  sinon.assert.calledWithNew(spy)  // SUCCESS
  sinon.assert.calledWithExactly(spy, { bank_acct: "1337" })  // SUCCESS
  done()
})

(请注意,我修改了测试以使用 calledWithExactly 来检查参数,因为 calledWithNew 在 v7.2.2 中似乎没有正确检查参数)

关于javascript - 如何检查在 Sinon 中是否使用正确的属性调用了类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53765872/

相关文章:

javascript - 单例菜单面板在 extjs 5 中不起作用

PHPUnit 测试实例

node.js - Node.js/Express 应用中的测试环境

javascript - 尝试 stub 函数

javascript - 在 module.exports 方法上使用 sinon 测试方法调用

javascript - 我无法在 laravel 5.2 中使用 ajax 将数据插入数据库

javascript - HTML 和 JS 中不同的字符串表示

javascript - -Infinity 是如何工作的?

tdd - 伪代码编程过程与测试驱动开发

javascript - 在Sinon.js和instanceof中模拟类