Categories
JavaScript Answers

How to have different return values for multiple calls on a Jasmine spy with JavaScript?

Spread the love

Sometimes, we want to have different return values for multiple calls on a Jasmine spy with JavaScript.

In this article, we’ll look at how to have different return values for multiple calls on a Jasmine spy with JavaScript.

How to have different return values for multiple calls on a Jasmine spy with JavaScript?

To have different return values for multiple calls on a Jasmine spy with JavaScript, we call returnValues with all the values we want to return.

For instance, we write

describe("A spy, when configured to fake a series of return values", () => {
  beforeEach(function () {
    spyOn(util, "foo").and.returnValues(true, false);
  });

  it("when called multiple times returns the requested values in order", () => {
    expect(util.foo()).toBeTruthy();
    expect(util.foo()).toBeFalsy();
    expect(util.foo()).toBeUndefined();
  });
});

to mock the util.foo method with spyOn in the beforeEach hook to create the mock before each test.

And then we call returnValues with all the values we want to return.

Then in the test, we call expect to check for each value returned by util.foo.

Conclusion

To have different return values for multiple calls on a Jasmine spy with JavaScript, we call returnValues with all the values we want to return.

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 *