Categories
JavaScript Answers

How to stub a promise with sinon and JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *