vue.js - 用 jest : $route is always undefined 进行 Vue 测试

标签 vue.js vuejs2 jestjs vue-router vue-test-utils

我已经尝试了很多东西,但是 $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/

相关文章:

vue.js - Uncaught ReferenceError : photoModule is not defined

javascript - Vue 2 从嵌套组件更新数组中对象的属性

javascript - Axios 在 Controller 返回对象对象中发送 formData

css - 在不使用 px 的情况下在右侧对齐的堆叠/覆盖 div

reactjs - 将 Jest 与 react-scripts 一起使用(通过 yarn 运行),如何在不必传递 watchAll 标志的情况下获得完整的覆盖率报告?

javascript - 在 Vuex getter 中访问 rootState

javascript - Vue.js : "Invalid or unexpected token" when using webpack. DefinePlugin()

javascript - Vue.js - JSON API 数据不会出现在点击事件上

javascript - 已超出 Jest Call 重试次数

next.js - 是否可以测试 Next.js 13 API 路由处理程序?