嘲弄/捣乱`超级'电话

Fot*_*ios 5 javascript unit-testing mocha.js sinon ecmascript-6

我想模拟super调用,特别是一些ES6类中的构造函数.例如

import Bar from 'bar';

class Foo extends Bar {
  constructor(opts) {
    ...
    super(opts);
  }

  someFunc() {
    super.someFunc('asdf');
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中,我想做类似的事情

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');
  });
})    
Run Code Online (Sandbox Code Playgroud)

Fot*_*ios 7

想出来了,@ 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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)