Doug Allrich
Doug Allrich

Reputation: 857

Mocking addEventListener in created hook

I'm trying to test an event listener in my App.vue created hook. The test passes the 1st assertion and fails on the 2nd. From what I can see in the terminal, the issue appears to be that the test is expecting [Function mockConstructor] but received [Function bound mockConstructor] as the 2nd parameter. I'm not sure what the issue is. Any pointers would be appreciated.

In App.vue component:

  async created () {
    window.addEventListener('orientationchange', this.changeHandler);

    await someModuleFunction();
    someOtherModuleFunction();
  },

  methods: {
    changeHandler () { /* Function code here. */ },
  }

In App.spec.js test:

import { createLocalVue, shallowMount } from '@vue/test-utils';
import App from '@/App';
import wait from 'waait';

const localVue = createLocalVue();
let windowSpy;
let mockAdd;

describe('app.vue', () => {
  beforeEach(() => {
    windowSpy = jest.spyOn(global, 'window', 'get');
    mockAdd = jest.fn();
    windowSpy.mockImplementation(() => ({
      addEventListener: mockAdd,
    }));
  });

  afterEach(() => {
    windowSpy.mockRestore();
    mockAdd.mockRestore();
  });

  const shallowMountFunction = (options = {}) => shallowMount(App, {
    localVue,
    stubs: ['router-view'],
    ...options,
  });

  describe('created hook', () => {
    it('calls the expected functions', async () => {
      expect.assertions(2);
      const spy = jest.spyOn(App.methods, 'changeHandler')

      shallowMountFunction();
      await wait();

      expect(mockAdd).toHaveBeenCalledTimes(1);
      expect(mockAdd).toHaveBeenCalledWith('orientationchange', spy);
    });
  });
})

Upvotes: 2

Views: 617

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

Vue component methods are bound to an instance, it isn't expected that this.changeHandler is the same function that were provided in methods.

It is:

const wrapper = shallowMountFunction();
...
expect(mockAdd).toHaveBeenCalledWith('orientationchange', wrapper.vm.changeHandler);

Upvotes: 1

Related Questions