59

I am pulling my hair out trying to figure out how to mock a constructor using sinon. I have a function that will create multiple widgets by calling a constructor that accepts a few arguments. I want to verify that the constructor is called the correct number of times with the correct parameters, but I don't want to actually construct the widgets. The following links seemingly explain a straightforward way of mocking the constructor, however it does not work for me:

Spying on a constructor using Jasmine

http://tinnedfruit.com/2011/03/25/testing-backbone-apps-with-jasmine-sinon-2.html

When I make the following call to stub the constructor:

sinon.stub(window, "MyWidget");

I get the following error:

Uncaught TypeError: Attempted to wrap undefined property MyWidget as function 

When debugging in Chrome I see MyWidget shows up in the Local section of the Scope Variables, however there is not MyWidget property off of window.

Any help would be greatly appreciated.

2
  • 3
    Beware, this post does not provide any actual solutions for the stated question.
    – C G-K
    Nov 8, 2021 at 18:36
  • To anyone else stumbling into this, it may not be possible 1, 2
    – apokryfos
    Nov 27, 2023 at 11:07

9 Answers 9

24

I needed a solution for this because my code was calling the new operator. I wanted to mock the object that the new call created.

var MockExample = sinon.stub();
MockExample.prototype.test = sinon.stub().returns("42");
var example = new MockExample();
console.log("example: " + example.test()); // outputs 42

Then I used rewire to inject it into the code that I was testing

rewiredModule = rewire('/path/to/module.js');
rewiredModule.__set__("Example", example);
8

From the official site of sinonjs:

Replaces object.method with a stub function. The original function can be restored bycalling object.method.restore(); (or stub.restore();). An exception is thrown if the property is not >already a function, to help avoid typos when stubbing methods.

this simply states that the function for which you want to create the stub must be member of the object object.

To make things clear; you call

sinon.stub(window, "MyWidget");

The MyWidget function needs to be within the global scope (since you pass window as parameter). However, as you already said, this function is in a local scope (probably defined within an object literal or a namespace).

In javascript everyone can have access to the global scope, but not the other way around.

Check where you declare the MyWidget function and pass container object as first parameter to sinon.stub()

3
  • Thanks ppoliani. That makes more sense. I am using dojo/require.js and I noticed that MyWidget is created in the global scope, but is namespaced according to my declare statement. So it exists in window.my.namespace.MyWidget. I was able to successfully mock/stub it in the global scope. Now my issue is inside the object that calls the MyWidget constructor, a local version is being used (from the define) rather than the global version that I have stubbed. Any idea on how I can force require.js to recognize the stubbed constructor? Jan 28, 2013 at 21:58
  • 1
    If you're using require.js then have you tried to add a dependency in your "test.js" file? /n For example, require(['ModuleUnderTest'], function(ModuleUnderTest){sinon.stub(ModuleUnderTest,'MyWidget')});. In any case, you need to load the module that contains the MyWidget constructor. Remember that a test file is like any other javascript file, it uses the same mechanism to locate the references.
    – ppoliani
    Jan 29, 2013 at 0:33
  • Thanks again, but that also does not work for me. The problem is I am following the AMD pattern, so the dependency is in the Closure and not accessible. I have spent the last few days trying different solutions including Testr.js, Squire.js, StubModule.js, as well as my own concoctions based on similar principles. So far nothing has worked for me. I think one of the main reasons is they are built for Require.js and I'm using dojo (I think dojo has a slightly different implementation of require). StubModule.js works with dojo, yet I have been unsuccessful getting it to work in my app. Feb 1, 2013 at 19:42
5

Using Sinon 4.4.2, I was able to mock an instance method like this:

const testObj = { /* any object */ }
sinon.stub(MyClass.prototype, "myMethod").resolves(testObj)
let myVar = await new MyClass(token).myMethod(arg1, arg2)
// myVar === testObj

A similar solution provided here: Stubbing a class method with Sinon.js

1
  • 37
    This doesn't address the question of how to mock the constructor of a class.
    – zedd45
    Feb 26, 2020 at 19:22
2

I used Mockery to Mock a Constructor/Function without any problems.

var mockery = require('mockery');
var sinon = require('sinon');

mockery.enable({
  useCleanCache: true,
  warnOnReplace: false,
  warnOnUnregistered: false
});

exports.Client = function() {/* Client constructor Mock */};
var ClientSpy = sinon.spy(exports, 'Client');
mockery.registerMock('Client', ClientSpy);

var Factory = require('Factory'); // this module requires the Client module

You should be able to apply a Sinon Spy just as the example above does.

Make sure to disable or reset Mockery after the test(s)!

1

Use sinon.createStubInstance(MyES6ClassName), then when MyES6ClassName is called with a new keyword, a stub of MyES6ClassName instance will returned.

1
  • 2
    This does not override the constructor.
    – C G-K
    Nov 8, 2021 at 18:34
1

Mocking and stubbing the constructor with sinon

I give two solutions. The first addresses the question, how to mock the constructor with behaviour, the second shows how to stub it with a dummy. Google guided me multiple times to this question for the search how to stub it.

Mocking the constructor with behaviour

I don't know if this is the shortest path. At least it does, what was asked for.

First I use sinon's fake method to create a mocking constructor Mock with the behaviour I want. Then I have to add the methods one by one. For reasons I didn't investigate, it did not work, when setting the whole prototype of UnderTest to Mock.

require('chai').should();
const { fake} = require('sinon');

class UnderTest {
  constructor() {
    this.mocked = false;
  }

  isMocked() {
    return this.mocked;
  }
}

describe('UnderTest', () => {
  let underTest;
  let isMocked;
  before(() => {
    const Mock = fake(function () { this.mocked = true; });
    Mock.prototype.isMocked = UnderTest.prototype.isMocked;
    underTest = new Mock();
    isMocked = underTest.isMocked();
  });
  it('should be mocked', () => {
    isMocked.should.be.true;
  });
});

Stubbing the constructor with a dummy

If you are leaded to this post, because you just want to stub the constructor to keep it from being executed.

Sinon's createStubInstance creates a stubbed constructor. It also stubs all methods. Hence, the method under test has to be restored before.

require('chai').should();
const { createStubInstance } = require('sinon');

class UnderTest {
  constructor() {
    throw new Error('must not be called');
  }

  testThis() {
    this.stubThis();
    return true;
  }

  stubThis() {
    throw new Error('must not be called');
  }
}

describe('UnderTest', () => {
  describe('.testThis()', () => {
    describe('when not stubbed', () => {
      let underTest;
      let result;
      before(() => {
        underTest = createStubInstance(UnderTest);
        underTest.testThis.restore();
        result = underTest.testThis();
      });
      it('should return true', () => {
        result.should.be.true;
      });
      it('should call stubThis()', () => {
        underTest.stubThis.calledOnce.should.be.true;
      });
    });
  });
});
0

I ran into this error by mistakenly typing sinon.stub.throws(expectedErr) rather than sinon.stub().throws(expectedErr). I've made similar mistakes before and not encountered this particular message before, so it threw me.

-1

Just found this in the documentation.

If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function.

var stub = sinon.createStubInstance(MyConstructor)

3
  • 37
    This does not mock a constructor. It creates a stubbed instance, as the name indicates, and does not modify the constructor in any way. This answer is not relevant to the question. Aug 24, 2017 at 14:27
  • 7
    Plus createStubInstance has been deprecated in latest versions of Sinon. Sep 11, 2017 at 13:46
  • 8
    createStubInstance hasn't been deprecated as of 6.3.4 sinonjs.org/releases/v6.3.4/utils
    – proteus
    Sep 27, 2018 at 22:46
-23

I was able to get StubModule to work after a few tweaks, most notably passing in async:false as part of the config when requiring in the stubbed module.

Kudos to Mr. Davis for putting that together

2
  • 52
    the question asks for a solution with Sinon. Why is this accepted?
    – cyrf
    Oct 12, 2016 at 21:43
  • 10
    I think OP accepted his own answer because it solved his particular problem in a way that was acceptable to him, however it does not answer the question so I agree this should not be the accepted answer. For people coming to the question later wanting to know the answer for sinon (like me), this isn't very helpful.
    – fool4jesus
    Aug 14, 2018 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.