Categories
JavaScript Answers

How to clear spy programmatically in Jasmine and JavaScript?

Spread the love

Sometimes, we want to clear spy programmatically in Jasmine and JavaScript.

In this article, we’ll look at how to clear spy programmatically in Jasmine and JavaScript.

How to clear spy programmatically in Jasmine and JavaScript?

To clear spy programmatically in Jasmine and JavaScript, we can just change the spy.

For instance, we write

let spyObj;
beforeEach(() => {
  spyObj = spyOn(obj, "methodName").and.callFake((params) => {});
});

it("should do the declared spy behavior", () => {
  // ...
});

it("should do what it used to do", () => {
  spyObj.and.callThrough();
});

it("should do something differently", () => {
  spyObj.and.returnValue("new value");
});

to create the spyObj object with spyOn.

Then we write spyObj.and.callThrough(); to call obj.methodName in the first test.

In the 2nd test, we call spyObj.and.returnValue to return a new mocked value for obj.methodName.

The existing spy will be cleared after each test.

Conclusion

To clear spy programmatically in Jasmine and JavaScript, we can just change the spy.

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 *