Cannot spyOn functions inside of Vue 3 setup()
Asked Answered
F

1

7

How can I write a test using Jest that invokes resetTimer and checks that startTimer is also invoked?

Code:

setup () {
    const startTimer = () => {
        // ...
    };

    const resetTimer = () => {
        startTimer();
    };

    return {
        startTimer,
        resetTimer
    }

Test:

import { shallowMount } from '@vue/test-utils';
import Overlay from '@/components/Overlay.vue';

const wrapper = shallowMount(Overlay);

it('resetTimer should call startTimer', () => {
    const spy = jest.spyOn(wrapper.vm, 'resetTimer');

    wrapper.vm.startTimer();
    expect(spy).toHaveBeenCalled();
});

Result:

TypeError: object.hasOwnProperty is not a function

      187 |
      188 |     it('resetTimer should call startTimer', () => {
    > 189 |         const spy = jest.spyOn(wrapper.vm, 'resetTimer');
          |                          ^
      190 |         wrapper.vm.startTimer();
      191 |         expect(spy).toHaveBeenCalled();
      192 |     });

Thanks!

Flinch answered 26/10, 2020 at 19:50 Comment(1)
Brilliant question, makes me wonder how mocking and spying will work in general with composition functions. Maybe you could replace setup on the component within the test, to execute the spy before it returns?Holle
D
-2

Found a temporary solution, not the best but at least lets you to check if the function it's called.

import { mount } from '@vue/test-utils';
import Component from './Component.vue';

describe('Component', () => {
  it('should call foo', () => {
    Component.created = function () {
      this.foo = jest.fn(this.foo);
    };
    const component = mount(Component);
    component.find('div').trigger('click');
    component.vm.foo();
    expect(component.vm.foo).toHaveBeenCalled();
    delete Component.created;
  });
});
Damalus answered 23/12, 2020 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.