详解Jest结合Vue-test-utils使用的初步实践

2020-06-14 06:26:38易采站长站整理

expect(wrapper.props().messages).toContain('bye')
});

有时候会对Props的Type、默认值或者通过validator对Prop进行自定义的验证


props: {
messages: {
type: Array,
required: true,
validator: (messages) = > messages.length > 1,
default () {
return [0, 2] }
}
},

通过Vue实例的$options获取包括Props在内的初始化选项:


// vm.$options返回Vue实例的初始化选项
describe('验证Props的各个属性', () = > {
wrapper = mount(Test1, {
propsData: {
messages: ['bye', 'bye', 'bye'] }
});
const messages = wrapper.vm.$options.props.messages;
it('messages is of type array', () = > {
expect(messages.type).toBe(Array)
});
it('messages is required', () = > {
expect(messages.required).toBeTruthy()
});
it('messages has at least length 2', () = > {
expect(messages.validator && messages.validator(['a'])).toBeFalsy();
expect(messages.validator && messages.validator(['a', 'a'])).toBeTruthy();
});
wrapper.destroy()
});

测试自定义事件

自定义事件要测试点至少有以下两个:

测试事件会被正常触发
测试事件被触发后的后续行为符合预期

具体到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();