使用 Jest,在 vue 中对单个文件组件进行单元测试时,我如何监视扩展组件的方法.js



我目前正在尝试使用Jest和vue-test-utils测试单个文件组件(ComponentB(单元。ComponentB扩展了ComponentA,其中update(product)定义了一个方法。

/* -------- Component B -------- */
<script>
import ComponentA from './ComponentA'
export default {
extends: ComponentA,
props: [...],
data: () => {
productData: {foo: 'bar', baz: 'shiz'}
},
methods: {
updateProduct() {
this.update(this.productData)
}
}
}
</script>
/* -------- Component A -------- */
<script>
export default {
props: [...],
data: () => {...},
methods: {
update(productData) {
...
}
}
}
</script>

然后,我尝试进行单元测试,在该测试中,我shallowMount()我的ComponentB并尝试jest.spyOnComponentA中定义的update(productData)方法。测试如下所示:

it('calls update with data when input is added to the field', () => {
const spy = jest.spyOn(ComponentA, 'update);
const wrapper = shallowMount(ComponentB, { propsData: { ... } });
const contractIdInput = wrapper.find('#contract-id-input > b-form-input');    
contractIdInput.element.value = 'foobar';
contractIdInput.trigger('input')
expect(spy).toHaveBeenCalledWith(...someDataHere...)
});

当我运行此测试时,我得到一个Cannot spy the update property because it is not a function; undefined given instead.

我不完全确定为什么这不起作用,尽管我确实有一些想法。

首先,因为我正在shallowMount()我的ComponentB,它不会知道关于它的父组件的任何信息,因此无法访问ComponentA上定义的update(productData)方法。

其次,也许我没有在正确的时间调用jest.spyOn(),而是应该在创建ComponentB的包装对象后调用它。但是,我尝试改变这一点,但没有任何成功或不同的行为。

所以我的问题是,当我浅层安装被测组件时,如何监视扩展组件提供的方法?

只是为了补充上面的@user2718281答案,SetMethods它已被弃用,所以你最好在像这样实例化之前定义指向 ComponentB 的 spyOn:

// create a spy before the instance is created
const spySomeMethod = jest.spyOn(ComponentB.methods, 'someMethod')
const spyUpdate = jest.spyOn(ComponentB.methods, 'update')
const wrapper = shallowMount(ComponentB, { propsData: { ... } });
// your tests ...
// verify the spy was called
expect(spyUpdate).toHaveBeenCalled();
// remove the spy
spyUpdate.mockReset();

关于这个问题,也许您忘记添加这样的ComponentA.methods

const spySomeMethod = jest.spyOn(ComponentB.methods, 'someMethod')

但是,如果要测试某些生命周期方法事件(如mountedcreated请像这样删除.methods

const spySomeMethod = jest.spyOn(ComponentB, 'created')
ComponentA

是一个组件定义,update作为methods属性的子级,因此update不会在ComponentAComponentB上找到。spyOn应改为应用于组件的实例。

const wrapper = shallowMount(ComponentB, { propsData: { ... } });
// create a spy on the instance method
const spyUpdate = jest.spyOn(wrapper.vm, 'update')
// replace the instance method with the spy
wrapper.setMethods({ update: spyUpdate });
// your tests ...
// verify the spy was called
expect(spyUpdate).toHaveBeenCalled();
// remove the spy
spyUpdate.mockReset();

最新更新