【发布时间】:2019-05-14 21:45:55
【问题描述】:
我正在测试从外部库中实例化对象的代码。为了使这个可测试,我决定注入依赖:
归结为:
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,然后锁定了数百万美元:我们希望它被存根、模拟和监视。
在我的测试中:
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() 被调用,工作正常,在 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 吗?如果是,怎么做?
【问题讨论】:
标签: javascript tdd sinon