如果要尝试模拟内部方法_setHeightOffset,则需要使用mount。
或者您可以使用浅安装,然后在余量上创建存根。
为什么? 因为headroom 有您自定义的 Test Vue 组件的子组件。如果您使用 shallowMount,哪个空间已自动存根。参考:shallowMount。
我创建了几个关于如何监视或模拟它的示例。您可以选择适合自己的。
// File: ComponentTest.spec.js
import { headroom } from 'vue-headroom';
import { mount, shallowMount } from '@vue/test-utils';
import Component from '@/components/ComponentTest.vue';
describe('ComponentTest.vue', () => {
it('example spy & mount', () => {
const spy = jest.spyOn(headroom.methods, '_setHeightOffset');
const wrapper = mount(Component);
expect(wrapper.vm).toBeTruthy();
expect(spy).toHaveBeenCalledTimes(2);
});
it('example mock & mount', () => {
const mock = jest.fn();
headroom.methods._setHeightOffset = mock;
const wrapper = mount(Component);
expect(wrapper.vm).toBeTruthy();
expect(mock).toHaveBeenCalledTimes(2);
});
it('example mock & shallow mount', () => {
const mock = jest.fn();
headroom.methods._setHeightOffset = mock;
const wrapper = shallowMount(Component, {
stubs: {
headroom,
},
});
expect(wrapper.vm).toBeTruthy();
expect(mock).toHaveBeenCalledTimes(2);
});
});
示例测试组件(简化)
// File ComponentTest.vue
<script>
import { headroom } from 'vue-headroom';
export default {
name: 'Test',
components: { headroom },
mounted() {
this.$refs.headroom._setHeightOffset();
},
};
</script>
<template>
<headroom ref="headroom">
xxx
</headroom>
</template>
然后我运行 jest 来运行 ComponentTest.spec.js
$ npx jest ComponentTest.spec.js
PASS test/ComponentTest.spec.js
ComponentTest.vue
✓ example spy & mount (12 ms)
✓ example mock & mount (2 ms)
✓ example mock & shallow mount (2 ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 2.176 s
注意:
我使用toHaveBeenCalledTimes(2)。为什么?因为headroom.vue内部已经调用了内部方法,你再尝试调用。