How to stub a promise with sinon and JavaScript?

Sometimes, we want to stub a promise with sinon and JavaScript.

In this article, we’ll look at how to stub a promise with sinon and JavaScript.

How to stub a promise with sinon and JavaScript?

To stub a promise with sinon and JavaScript, we can return a promise with a stub.

For instance, we write

import sinon from "sinon";

const sandbox = sinon.sandbox.create();

const promiseResolved = () =>
  sandbox.stub().returns(Promise.resolve("resolved"));
const promiseRejected = () =>
  sandbox.stub().returns(Promise.reject("rejected"));

to call sandbox.stub to return a stub.

And we make it return a promise by calling returns with a promise.

Promise.resolve returns a promise that resolves.

And Promise.reject returns a promise that rejects.

Conclusion

To stub a promise with sinon and JavaScript, we can return a promise with a stub.