【问题标题】:How to make Vue3 test utils work with teleport如何使 Vue3 测试工具与 Teleport 一起使用
【发布时间】:2021-06-29 13:18:17
【问题描述】:

我有一个使用 Teleport to 的组件,测试 html 似乎没有按预期工作。我找不到有关此特定用途的任何文档。这是我的测试:

describe('MetaHead', () => {
  it('dynamic metadata tags contain custom text', () => {

    let title = 'My Page';
    let description = 'Some description about my page';
    // This component uses Vue3's teleport to tag <head>
    // we must modify wrapper to contain such tag
    document.body.innerHTML = `
      <head>
        <div id="app"></div>
      </head>
    `

    const wrapper = mount(MetaHead, {
      attachTo: document.getElementById('app'),
      props: { 
        title,
        description
      },
      global:{
        mocks: {
          $route:{fullPath: 'full/path'}
        } 
      }
    })
    expect(wrapper.html()).toContain(title)
    expect(wrapper.html()).toContain(description)
  })
})

最小的组件看起来像这样:

<template>
  <teleport to="head">
    <title>{{title}}</title>
    <meta property="og:site_name" :content="title">
    <meta name="description" :content="description">
  </teleport>
</template>

我错过了什么吗?

【问题讨论】:

  • 当前包装器正在获取:收到的字符串:“
  • 我最终添加了一个道具来使用组件标签禁用传送,如果它被禁用则呈现一个 div。
  • 在尝试测试基于传送的第 3 方组件(例如 PrimeVue 对话框)的内容时存在类似问题。

标签: vuejs3 vue-test-utils vue-teleport


【解决方案1】:

这里的问题是wrapper.html() 只在您的组件中返回 HTML - 因为您将传送 您的组件,当您调用 wrapper.html() 时,该标记不会显示。

您有几个选择。一种是针对document.body.outerHTML 作出断言。另一个是使用findComponent 的巧妙技巧,我写了关于它here 并发布了一个关于它的视频here

我刚刚想到(但尚未测试)您可以尝试的另一件事是:

mount({
  template: `
    <div id="app" />
    <MetaHead />
  `,
  components: { MetaHead }
})

我不知道这是否可行,但值得一试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2015-12-08
    • 1970-01-01
    • 2011-08-12
    • 2022-09-30
    • 2019-01-12
    • 2011-02-06
    • 2021-10-27
    相关资源
    最近更新 更多