我已经尝试了很多东西,但 $route 似乎总是未定义,并且我在shallowMount上遇到此错误:
TypeError: Cannot read property 'params' of undefined
。
在我的组件中,我想检查 $route 的参数,但它总是未定义。我查看了文档并嘲笑了
$route
来设置它,但似乎 $route 没有被嘲笑。我也尝试过使用 localVue.use(VueRouter) ,认为它会设置 $route 但事实并非如此。有谁知道为什么以下两种情况都不起作用?
我的组件.ts
@Component
export default class MyComponent extends Vue {
get organisationId() {
return this.$route.params.organisationId;
}
}
我已经使用我谈到的解决方案尝试了以下 2 个测试:
我的组件.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();
});
});
我的组件.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();
});
});
你在#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')
})
})
我知道我是在两年后回答我的问题,但我认为它可以帮助有同样问题的人,所以这是我解决它的方法:
在我的组件中,我使用了一个指令,但我忘记在我的 localVue 实例中使用它。这个错误根本没有让我想到这一点。当你在组件中使用指令时,你应该添加
import directive from '@/directives/my-directive';
const localVue = createLocalVue();
localVue.directive('myDirective', directive);