Javascript 模仿/打断“超级”呼叫

Javascript 模仿/打断“超级”呼叫,javascript,unit-testing,mocha.js,ecmascript-6,sinon,Javascript,Unit Testing,Mocha.js,Ecmascript 6,Sinon,我想模拟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';

我想模拟
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);
    });
  });
});

super
关键字用作函数调用时,它调用基类构造函数。您的
someFunc
示例可能应该是
super.someFunc('asdf')
它不需要是
sinon.stub(Bar.prototype,'someFunc')?否,您不能存根已从继承的构造函数。您需要在
foo.js
中插入受监督版本的
Bar
。为什么要测试实现?为什么不测试输入/输出?@Amit:你说得对,我的示例中有一个输入错误。请注意,这是因为Babel通过
Class.prototype.constructor
查找实现ES6
super
调用,而本机ES6类通过
Object.getPrototypeOf(Class)
查找父构造函数,在较旧的浏览器上无法进行多填充。我想你需要
sandbox.stub(Memcached,'.\uu proto'.''.\uu')