详解Jest结合Vue-test-utils使用的初步实践(5)
测试自定义事件
自定义事件要测试点至少有以下两个:
- 测试事件会被正常触发
- 测试事件被触发后的后续行为符合预期
具体到Test1组件和MyButton组件来看:
TEST1组件:
// TEST1
<MyButton class="my-button" style="padding-top: 10px" buttonValue="Me" @add="addCounter"></MyButton>
// 省略一些代码
methods: {
addCounter(value) {
this.count = value
}
},
MyButton组件:
<button @click="increment">Click {{buttonValue}} {{innerCount}}</button>、
// 省略一些代码
data() {
return {
innerCount: 0
}
},
computed: {},
methods: {
increment() {
this.innerCount += 1;
this.$emit('add', this.innerCount)
}
},
要测试的目的是:
1. 当MyButton组件的按钮被点击后会触发increment事件
2. 点击事件发生后,Test1组件的addCounter函数会被触发并且结果符合预期(及数字递增)
首先为MyButton编写单元测试文件:
describe('Test for MyButton Component', () => {
const wrapper = mount(MyButton);
it('calls increment when click on button', () => {
// 创建mock函数
const mockFn = jest.fn();
// 设置 Wrapper vm 的方法并强制更新。
wrapper.setMethods({
increment: mockFn
});
// 触发按钮的点击事件
wrapper.find('button').trigger('click');
expect(mockFn).toBeCalled();
expect(mockFn).toHaveBeenCalledTimes(1)
})
});
通过setMethods方法用mock函数代替真实的方法,然后就可以断言点击按钮后对应的方法有没有被触发、触发几次、传入的参数等等。
现在我们测试了点击事件后能触发对应的方法,下面要测试的就是increment方法将触发Test1组件中自定义的add方法
// increment方法会触发add方法
it('triggers a addCounter event when a handleClick method is called', () = > {
const wrapper = mount(MyButton);
// mock自定义事件
const mockFn1 = jest.fn();
wrapper.vm.$on('add', mockFn1);
// 触发按钮的点击事件
wrapper.find('button').trigger('click');
expect(mockFn1).toBeCalled();
expect(mockFn1).toHaveBeenCalledWith(1);
// 再次触发按钮的点击事件
wrapper.find('button').trigger('click');
expect(mockFn1).toHaveBeenCalledTimes(2);
expect(mockFn1).toHaveBeenCalledWith(2);
})
这里使用了$on方法,将Test1自定义的add事件替换为Mock函数
对于自定义事件,不能使用trigger方法触发,因为trigger只是用DOM事件。自定义事件使用$emit触发,前提是通过find找到MyButton组件
// $emit 触发自定义事件
describe('验证addCounter是否被触发', () = > {
wrapper = mount(Test1);
it('addCounter Fn should be called', () = > {
const mockFn = jest.fn();
wrapper.setMethods({
'addCounter': mockFn
});
wrapper.find(MyButton).vm.$emit('add', 100);
expect(mockFn).toHaveBeenCalledTimes(1);
});
wrapper.destroy()
});
内容版权声明:除非注明,否则皆为本站原创文章。
