Sometimes, we want to spy on function with Jest and JavaScript.
In this article, we’ll look at how to spy on function with Jest and JavaScript.
How to spy on function with Jest and JavaScript?
To spy on function with Jest and JavaScript, we use the spyOn method.
For instance, we write
import { mount } from "enzyme";
describe("My component", () => {
it("should call getData", () => {
const spy = jest.spyOn(Component.prototype, "getData");
mount(<Component />);
expect(spy).toHaveBeenCalledTimes(1);
});
});
to call spyOn on the Component‘s getData instance method with spyOn.
Then we call mount to mount the Component.
And then we call toHaveBeenCalledTimes with 1 to check if getData has been called once.
Conclusion
To spy on function with Jest and JavaScript, we use the spyOn method.