我已经尝试了很多东西,但是 $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 测试中就在 mock $route
。您可以通过 wrapper.vm.$route
(或您的情况下的 cmp.vm.$route
)访问测试组件的 $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')
})
})
关于vue.js - 用 jest : $route is always undefined 进行 Vue 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67328280/