首页 文章

使用Vue-Router进行快照测试

提问于
浏览
1

我正在尝试在使用Vue-cli应用程序创建的Vue应用程序中运行jest-snapshot测试 . 当我测试其中包含路由器链接的组件时,我收到以下警告 .

[Vue warn]: Unknown custom element: <router-link> - did you register 
 the component correctly? For recursive components, make sure to 
 provide the "name" option.

按照此处的文档Unit tests with View Router我可以存根路由器链接,但这不会通过我的快照测试 . 有没有人遇到过这个问题?

1 回答

  • 2

    Updated: A more consistent solution

    TL;博士:

    我发现一致的解决方案是创建 localVue (通常超出 describe() 块的范围)并添加 RoutherLinkStub 作为组件 .

    import { mount, RouterLinkStub, createLocalVue } from '@vue/test-utils';
    
    const localVue = createLocalVue();
    localVue.component('router-link', RouterLinkStub);
    
    const wrapper = mount(Component, { localVue });
    

    该文档并没有使解决方案显而易见,因为它似乎是您链接到的页面的混合,而这个关于RouterLinkStub .

    从该页面:

    import { mount, RouterLinkStub } from '@vue/test-utils'
    
    const wrapper = mount(Component, {
      stubs: {
        RouterLink: RouterLinkStub
      }
    })
    

    该解决方案适用于大多数情况 . 如果您需要使用 mount 并且 router-link 不是正在测试的组件而是在其下方的组件中,您仍然会收到该警告 . 现在,如果你处于那种情况,那么's worth reflecting if you'正确地编写你的测试(你测试的太多而不是一个小单位吗?),但我有一两种情况,如果我 shallow 而不是 mount ,快照测试毫无 Value 因为它将子项呈现为 <!----> when I call expect(wrapper.html()) . toMatchSnapshot()` .

    A Note on Snapshot Tests: 我实际上没有看到人们使用 Wrapper.html() 方法进行快照测试的例子,但它实际上似乎是我实验中的最佳解决方案 . vue-server-renderer 是一个漫长的步行,似乎是相同的结果 . 访问 Wrappervm 属性可以让您访问 $el 属性,没有太多麻烦,但它只是一个更加空白的 html() 渲染 .

相关问题