我正在测试从外部库实例化对象的代码。为了使其可测试,我决定注入(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/