fake a method with sinon in javascript

To fake a method with Sinon in JavaScript, you can use the replace() method. Here's an example:

// Let's say you have an object with a method you want to replace
const myObj = {
  myMethod: () => {
    return 'Original method result';
  }
};

// Now, in your test, you can replace myMethod with a fake function using sinon
const sinon = require('sinon');

// Create a fake function
const fakeMethod = sinon.fake.returns('Fake method result');

// Replace the original method with the fake one
sinon.replace(myObj, 'myMethod', fakeMethod);

// Now, when you call the method, it will return the result of the fake function
const result = myObj.myMethod(); // "Fake method result"

// Don't forget to restore the original method after your test
sinon.restore();
663 chars
22 lines

In this example, we create an object called myObj with a method called myMethod. We then use Sinon to create a fake function called fakeMethod that returns "Fake method result". We replace the original method with the fake one using sinon.replace(). Finally, we call myMethod() and it returns the result of fakeMethod. After our test, we restore the original method using sinon.restore().

gistlibby LogSnag