在创建的钩子中模拟 addEventListener

Mocking addEventListener in created hook

我正在尝试在 App.vue created 挂钩中测试事件侦听器。测试通过第一个断言并在第二个断言上失败。从我在终端中看到的情况来看,问题似乎是测试期望 [Function mockConstructor] 但接收到 [Function bound mockConstructor] 作为第二个参数。我不确定是什么问题。任何指针将不胜感激。

App.vue组件中:

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

    await someModuleFunction();
    someOtherModuleFunction();
  },

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

App.spec.js测试中:

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

Vue 组件方法绑定到一个实例,预计this.changeHandlermethods 中提供的功能不同。

是:

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