Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub static methods with sinon in ES6?

Tags:

var MyClassStub = sinon.createStubInstance(MyClass); 

MyClassStub doesn't contain static methods. How to fix that?

like image 623
Rostislav Shtanko Avatar asked Jul 06 '16 07:07

Rostislav Shtanko


People also ask

What is static method in es6?

As MDN describes it, “Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.” In other words, static methods have no access to data stored in specific objects.

What is Sinon stub ()?

The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called. For example, the below code stubs out axios.

How to stub a dependency of a module?

To stub a dependency (imported module) of a module under test you have to import it explicitly in your test and stub the desired method. For the stubbing to work, the stubbed method cannot be destructured, neither in the module under test nor in the test.


1 Answers

static method:

sinon.stub(YourClass, 'yourClassMethod').callsFake(() => {   return {} }) 

not static method:

sinon.stub(YourClass.prototype, 'yourClassMethod').callsFake(() => {   return {} }) 
like image 161
danday74 Avatar answered Oct 20 '22 18:10

danday74