Sinon stub static method

Sinon stub static method

To stub a static method using Sinon.js, you can use the sinon.stub function and the ES6 class syntax. Here’s an example:


class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

const sinon = require('sinon');
const mathStub = sinon.stub(MathUtils, 'add').returns(10);

console.log(MathUtils.add(2, 3)); // Output: 10
  

In the example above, we have a static method add in the MathUtils class. We then use sinon.stub to stub the add method of the MathUtils class and make it return 10.

By stubbing the static method, any calls to MathUtils.add will instead return the stubbed value (10 in this case) rather than executing the actual implementation. It allows you to control the behavior of the static method during tests or any other scenarios where you want to override its behavior.

Similar post

Leave a comment