【问题标题】:Mocking addEventListener in created hook在创建的钩子中模拟 addEventListener
【发布时间】:2021-08-01 09:15:07
【问题描述】:

我正在尝试在 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);
    });
  });
})

【问题讨论】:

    标签: javascript vue.js jestjs mocking vue-test-utils


    【解决方案1】:

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

    它是:

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

    【讨论】:

    • 非常有帮助。谢谢!
    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2021-05-11
    • 2021-11-24
    • 2011-09-18
    相关资源
    最近更新 更多