Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking/Stubbing `super` calls

I would like to mock out super calls, especially constructors in some ES6 classes. For example

import Bar from 'bar';

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

  someFunc() {
    super.someFunc('asdf');
  }
}

And then in my test, I would like to do something like

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');
  });
})    
like image 371
Fotios Avatar asked Aug 26 '15 15:08

Fotios


1 Answers

Figured it out, and @Bergi was on the right track. In reponse to @naomik's question - My main purpose for wanting to stub this out was two fold. First, I didn't want to actually instantiate the super class, merely validate that I was calling the proper thing. The other reason (which didn't really come through since I was trying to simplify the example), was that what I really cared about was that I was doing certain things to opts that I wanted to make sure were carried through properly to the super constructor (for example, setting default values).

To make this work, I needed to dosinon.stub(Bar.prototype, 'constructor');

This is a better example and working test.

// 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);
    });
  });
});
like image 197
Fotios Avatar answered Sep 28 '22 05:09

Fotios