Skip to content

Bug: Mock a function in a function #1798

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

Closed
mattaiod opened this issue Oct 6, 2022 · 1 comment
Closed

Bug: Mock a function in a function #1798

mattaiod opened this issue Oct 6, 2022 · 1 comment
Labels
bug Something isn't working

Comments

@mattaiod
Copy link

mattaiod commented Oct 6, 2022

Describe the bug
Mocking a function in a function in a Vue component if these 2 functions are declared in the same vue file doesn't work.

To Reproduce
Minimum reproduction:
https://github.com/mattaiod/VITEST-cant-mock-fn-in-fn-in-component

Expected behavior
Since I have mocked fnInside with 1 and fnInside is returned in fnOutside, I should get 1 and not 10

Related information:

  • @vue/test-utils: 2.1.0
  • vitest: 0.23.4
  • Vue: 3.2.40
  • node: v16.13.1
  • pnpm: 7.8.0
@mattaiod mattaiod added the bug Something isn't working label Oct 6, 2022
@cexbrayat
Copy link
Member

@mattaiod Thanks for the repro

Your test is using global.mocks, but its purpose is to mock variables injected by third-party plugins as outlined in the docs https://test-utils.vuejs.org/api/#global-mocks

You could try wrapper.vm.fnInside = vi.fn().mockReturnValue(1) but I think that will fail.
I don't think what you trying to do is doable. Think of it that way:

it('should mock the function fnInside', () => {
    // this is the setup of your component
    const factory = () => {
      const fnInside = () => 10
      const fnOutside = () => fnInside()
      return { fnInside, fnOutside }
    }
   // this is the mount(Component)
    const obj = factory()
   // override fnInside
    obj.fnInside = vi.fn().mockReturnValue(1)
    expect(obj.fnInside()).toBe(1)
    expect(obj.fnOutside()).toBe(1) // fails, returns 10, because it uses an internal reference to fnInside and not our override
})

Usually, you'll want to mock a function call to something external to your component (a HTTP call, a call to a composable, etc).
In that case, it's pretty straightforward using vi.mock

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