我尝试了很多方法,但 $route 似乎总是未定义,并且在shallowMount 上出现此错误:TypeError: Cannot read property 'params' of undefined
。
在我的组件中,我想检查 $route 的参数,但它始终未定义。我查看了文档并模拟了 $route
来设置它,但似乎 $route 没有被模拟。我也试过使用 localVue.use(VueRouter),认为它会设置 $route 但它没有。有谁知道为什么以下两种情况都不起作用?
my-component.ts
@Component
export default class MyComponent extends Vue {
get organisationId() {
return this.$route.params.organisationId;
}
}
我已经使用我提到的解决方案尝试了以下 2 个测试:
my-component.spec.ts
import { createLocalVue, shallowMount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';
import router from '@/router';
const localVue = createLocalVue();
describe('MyComponent', () => {
let cmp: any;
beforeEach(() => {
cmp = shallowMount(MyComponent, {
localVue,
router,
mocks: {
$route: {
params: {
id: 'id'
}
}
}
});
});
it('Should render a Vue instance', () => {
expect.assertions(1);
expect(cmp.isVueInstance()).toBeTruthy();
});
});
my-component.spec.ts
import { createLocalVue, shallowMount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';
const localVue = createLocalVue();
describe('MyComponent', () => {
let cmp: any;
localVue.use(VueRouter);
const router = new VueRouter();
beforeEach(() => {
cmp = shallowMount(MyComponent, {
localVue,
router
});
});
it('Should render a Vue instance', () => {
expect.assertions(1);
expect(cmp.isVueInstance()).toBeTruthy();
});
});
答案 0 :(得分:0)
您在 #1 测试中就对 $route
进行了嘲讽。您可以通过 $route
(或 wrapper.vm.$route
在您的情况下)访问测试组件的 cmp.vm.$route
属性。还有一个例子:
import { shallowMount, Wrapper } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
let wrapper: Wrapper<MyComponent>
describe('MyComponent', () => {
beforeEach(() => {
wrapper = shallowMount(MyComponent, {
mocks: {
$route: {
params: {
id: 'id'
}
}
}
})
})
it('$route has passed params', () => {
expect(wrapper.vm.$route.params.id).toBe('id')
})
})