【问题标题】:Vue testing with jest: $route is always undefined用 jest 进行 Vue 测试:$route 始终未定义
【发布时间】:2021-07-23 11:10:36
【问题描述】:

我尝试了很多东西,但 $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();
  });
});

【问题讨论】:

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


    【解决方案1】:

    你在 #1 测试中嘲笑 $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')
      })
    })
    

    【讨论】:

    • 遗憾的是,我在模拟 $route 时仍然遇到错误,我真的不明白为什么
    • 奇怪.. 希望你注意到我在测试中既没有导入router 对象也没有创建VueRouter 的新实例。
    • 是的,我也这样做了,但我发现了问题!在我的组件中,我使用了一个指令,但我忘记在我的 localVue 实例中使用它。该错误根本没有导致我这样做,但我终于解决了它!感谢您的帮助爱德华多
    猜你喜欢
    • 2017-06-11
    • 2020-10-19
    • 2020-05-08
    • 2017-07-20
    • 2021-04-24
    • 2020-07-13
    • 2021-08-02
    • 2020-01-01
    • 1970-01-01
    相关资源
    最近更新 更多