[removed] Mocking Constructor using Sinon

2020-05-29 12:50发布

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.

8条回答
不美不萌又怎样
2楼-- · 2020-05-29 13:31

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.

查看更多
Bombasti
3楼-- · 2020-05-29 13:32

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

查看更多
Evening l夕情丶
4楼-- · 2020-05-29 13:32

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

查看更多
老娘就宠你
5楼-- · 2020-05-29 13:38

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

查看更多
Anthone
6楼-- · 2020-05-29 13:42

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)!

查看更多
够拽才男人
7楼-- · 2020-05-29 13:44

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)

查看更多
登录 后发表回答