我想模拟一下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');
});
})
弄清楚了,@Bergi 走在正确的轨道上。
回答 @naomik 的问题 - 我想要解决这个问题的主要目的有两个。首先,我不想实际实例化超类,只是验证我调用的是正确的东西。另一个原因(因为我试图简化这个例子,所以没有真正实现),我真正关心的是我正在做某些事情opts
我想确保正确地进行到super
构造函数(例如,设置默认值)。
为了完成这项工作,我需要做sinon.stub(Bar.prototype, 'constructor');
这是一个更好的示例和工作测试。
// bar.js
import Memcached from 'memcached'
export default class Bar extends Memcached {
constructor(opts) {
super(opts);
}
}
// foo.js
import Bar from './bar.js';
export default class Foo extends Bar {
constructor(opts) {
super(opts);
}
}
// test.js
import Foo from './foo.js';
import Bar from './bar.js';
import Memcached from 'memcached';
import sinon from 'sinon';
let sandbox;
let memcachedStub;
const opts = '127.0.0.1:11211';
describe('constructors', function() {
beforeEach(function() {
sandbox = sinon.sandbox.create();
memcachedStub = sandbox.stub(Memcached.prototype, 'constructor');
});
afterEach(function() {
sandbox.restore();
});
describe('#bar', function() {
it('should call super', function() {
new Bar(opts);
sinon.assert.calledOnce(memcachedStub);
sinon.assert.calledWithExactly(memcachedStub, opts);
});
});
describe('#foo', function() {
it('should call super', function() {
new Foo(opts);
sinon.assert.calledOnce(memcachedStub);
sinon.assert.calledWithExactly(memcachedStub, opts);
});
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)