How to mock methods on a Vue.js instance in tests?

Sometimes, we want to mock methods on a Vue.js instance in tests.

In this article, we’ll look at how to mock methods on a Vue.js instance in tests.

How to mock methods on a Vue.js instance in tests?

To mock methods on a Vue.js instance in tests, we can use jest.spyOn.

For instance, we write

import MyComponent from "@/components/MyComponent.vue";

describe("MyComponent", () => {
  it("click does something", async () => {
    const mockMethod = jest.spyOn(MyComponent.methods, "doSomething");
    await shallowMount(MyComponent).find("button").trigger("click");
    expect(mockMethod).toHaveBeenCalled();
  });
});

to add a test that spies on the MyComponent‘s doSomething method with

jest.spyOn(MyComponent.methods, "doSomething")

Then we click the button that triggers doSomething to run with

await shallowMount(MyComponent).find("button").trigger("click");

And then we check that doSomething is called after button click with

expect(mockMethod).toHaveBeenCalled();

Conclusion

To mock methods on a Vue.js instance in tests, we can use jest.spyOn.