Categories
JavaScript Answers

How to modify Jasmine spies based on arguments with JavaScript?

Spread the love

Sometimes, we want to modify Jasmine spies based on arguments with JavaScript.

In this article, we’ll look at how to modify Jasmine spies based on arguments with JavaScript.

How to modify Jasmine spies based on arguments with JavaScript?

To modify Jasmine spies based on arguments with JavaScript, we can use the withArgs method.

For instance, we write

describe("user test", () => {
  it("gets user name and ID", () => {
    spyOn(externalApi, "get")
      .withArgs("abc")
      .and.returnValue("Jane")
      .withArgs("123")
      .and.returnValue(98765);
  });
});

to call withArgs with the arguments that we want to call externalApi.get with.

And then we call returnValue to mock the returned value given the argument we called withArgs with.

And we call withArgs and returnValue a 2nd time to call externalApi.get with the 2nd argument and mock its returned value given the argument.

Conclusion

To modify Jasmine spies based on arguments with JavaScript, we can use the withArgs method.

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 *