测试vue-router
Vue Router是官方客户端路由库。如果要给Vue应用程序添加客户端路由,你会用到Vue Router。因此,学习测试使用了Vue Router的应用程序是很有必要的。
测试路由属性
当Vue Router被安装到Vue上时,它会添加两个实例属性:$route属性和$router属性。这些属性应该带有一个巨大的警告标志,因为它们可能会在测试中造成很多问题。
测试$route属性
如果组件使用了$route实例属性,则该属性将成为组件的依赖项。当测试具有依赖关系的组件时,你需要模拟依赖关系以防止发生错误。
在测试用例中我们使用shallowMount()方法的配置对象的mocks提供一个假$route,下面是一个简单的示例:
import {
shallowMount} from '@vue/test-utils';
test('render id param',()=>{
const wrapper = shallowMount(TestComponent,{
mocks:{
$route:{
params:{
id:123
}
}
}
});
expect(wrapper.text()).toContain('123');
});
如果想与store配合,就在shallowMount()方法的配置对象中在添加一个假store。
test('dispaches fetchListData width params.type',async () => {
expect.assertins(1);
const store = createStore();
store.dispatch = jest.fn(()=> {
return Promise.resolve();
});
const type = 'a type';
const mocks = {
$route:{
params:{
type
}
},
store
}
await flushPromises();
expect(store.dispatch).toHaveBeenCalledWith('fetchListData',{
type});
});
测试$router属性
$router是一个路由实例,它包含了以编程方式控制路由的辅助方法。由于 r o u t e r 是一个实例属性,因此你可以使用 V u e T e s t U t i l s 的 m o c k s 挂载项在测试中控制 router是一个实例属性,因此你可以使用Vue Test Utils的mocks挂载项在测试中控制 router是一个实例属性,因此你可以使用VueTestUtils的mocks挂载项在测试中控制router的值。
test('call $router.replace',async ()=>{
expect.assertions(1);
const store = createStore({
getters:{
maxPage:()=> 5
}
});
const mocks = {
$route:{
params:{
page:'1000'
}
},
$router:{
replace:jest.fn()
}
}
createWrapper({
mocks,store});
await flushPromises();
// 断言$router.replace被正确的参数调用 expect(mocks.$router.replace).toHaveBeenCallWith('/top/1');
});