【发布时间】:2015-11-20 18:06:28
【问题描述】:
我想模拟 super 调用,尤其是一些 ES6 类中的构造函数。例如
import Bar from 'bar';
class Foo extends Bar {
constructor(opts) {
...
super(opts);
}
someFunc() {
super.someFunc('asdf');
}
}
然后在我的测试中,我想做类似的事情
import Foo from '../lib/foo';
import Bar from 'bar';
describe('constructor', function() {
it('should call super', function() {
let opts = Symbol('opts');
let constructorStub = sinon.stub(Bar, 'constructor');
new Foo(opts);
sinon.assert.calledWith(constructorStub, opts);
});
})
describe('someFunc', function() {
it('should call super', function() {
let funcStub = sinon.stub(Bar, 'someFunc');
let foo = new Foo(opts);
foo.someFunc();
sinon.assert.calledWith(funcStub, 'asdf');
});
})
【问题讨论】:
-
super关键字作为函数调用时,调用基类构造函数。你的someFunc样本应该是super.someFunc('asdf') -
不需要
sinon.stub(Bar.prototype, 'someFunc');吗? -
不,您不能存根已经继承自的构造函数。您需要在
foo.js中注入您的Bar监督版本。 -
为什么要测试实现?为什么不只测试输入/输出?
-
@Amit:你说得对,这是我的例子中的一个错字。
标签: javascript unit-testing mocha.js ecmascript-6 sinon