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!

Matt
  • 8,758
  • 4
  • 35
  • 64
Chateau
  • 71
  • 4
  • 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? – Matt Oct 27 '20 at 09:02

1 Answers1

-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;
  });
});