我想模拟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
构造函数(例如,设置默认值)。
为了完成这项工作,我需要dosinon.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);
});
});
});