Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Cannot spyOn methods when using the composition api (setup) #1830

Closed
tongvantruong opened this issue Oct 25, 2022 · 1 comment
Closed
Labels
bug Something isn't working

Comments

@tongvantruong
Copy link

tongvantruong commented Oct 25, 2022

Describe the bug

I tried solutions from this #775 but they don't work on my side.

MyComponent.vue

<template>
  <div @click="methodA"> </div>
</template>

<script setup lang="ts">
const methodA = () => {
  console.log("methodA");
  methodB();
};

const methodB = () => {
  console.log("methodB");
};
</script>

MyComponent.spec.ts

import { mount } from "@vue/test-utils";
import MyComponent from "./MyComponent.vue";

it("a", () => {
  const wrapper = mount(MyComponent);
  const spy = jest.spyOn(wrapper.vm, "methodB");
  wrapper.vm.methodA();
  expect(spy).toHaveBeenCalled();
});

=> Error

 expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

       7 |   const spy = jest.spyOn(wrapper.vm, "methodB");
       8 |   wrapper.vm.methodA();
    >  9 |   expect(spy).toHaveBeenCalled();
         |               ^
      10 | });

To Reproduce

Expected behavior

The test should be passed

Related information:

  • @vue/test-utils version: ^2.0.2
  • Vue version: ^3.2.37
  • node version: 16.14.2
  • npm (or yarn) version: yarn 1.22.17

Additional context

@tongvantruong tongvantruong added the bug Something isn't working label Oct 25, 2022
@freakzlike
Copy link
Collaborator

Spying and mocking is using the same technique by replacing the original function. But this only works for functions which are part of an object and accessible from outside. That's not vue specific and the same thing for common js modules as well. So unfortunately this is not possible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants