【发布时间】: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