【问题标题】:Vue Typescript Component Jest Testing doesn't render values in htmlVue Typescript 组件 Jest 测试不会在 html 中呈现值
【发布时间】:2021-02-02 17:48:15
【问题描述】:

我正在尝试使用 Typescript 专注于 TDD,因此我使用 vue-cli 构建了一个新的 Vue 项目(我选择使用 Vue3、Typescript 和 Jest)。但是,当我开箱即用地运行单元测试时,它失败了。经过一番调查,我发现来自@vue/test-utilsmount 命令不会呈现任何道具值:

HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    {{ test }}
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";

@Options({
  props: {
    msg: String,
  }
})
export default class HelloWorld extends Vue {
  msg!: string;
  test: string = "It's a test";
}
</script>

example.specs.ts

import { mount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("renders props.msg when passed", async () => {
    const msg = "new message";
    const wrapper = mount(HelloWorld, {
      props: { msg }
    });
    
    expect(wrapper.text()).toContain(msg);
  });
});

当我打印 wrapper.html() 时,我得到以下信息:

<div class="hello" msg="new message"><h1></h1></div>

它似乎根本没有将msgtest 渲染到html 中。它已将其列为道具,仅此而已。

我认为其中一个原因可能是我使用的是 Typescript 组件而不是传统的组件,这可能会导致它失败,但我不确定。

有什么建议/提示吗?

【问题讨论】:

    标签: typescript unit-testing vue.js jestjs vue-cli


    【解决方案1】:

    这个问题被跟踪到 vue-jest。刚刚修好了。 https://github.com/vuejs/vue-jest/pull/299

    【讨论】:

      【解决方案2】:
      1. 您的 HelloWorld 组件未被检测为组件,这就是您需要定义它的方式:

        @Component
        export default class HelloWorld extends Vue {
          @Prop() msg!: string;
        

      @Component 告诉编译器它是一个组件。

      @Prop() 告诉编译器 msg 属性是一个 prop。

      1. 使用 propsData 作为挂载选项或使用 setProps documentation link:

        const wrapper = mount(HelloWorld, {
          propsData: {
            msg, // or msg: msg, 
          },
        });
        

      结果:

        console.log tests/unit/example.spec.ts:13
          <div class="hello">
            <h1>
              new message
            </h1>
            It's a test
          </div>
      

      【讨论】:

      • 感谢您的回复。虽然我仍然无法让它工作,但那是因为我目前正在使用 Vue 3,所以我一直在跳下那个兔子洞。如果一切都失败了,我一定会切换回去并使用 Vue 2。
      【解决方案3】:

      所以这并不能完全解决问题,但这是我要尝试的另一种方法:我没有使用基于类的组件,而是更多地使用基于功能的 typescript 实现。

      HelloWorld.vue

      <template>
        <div class="hello">
          <h1>{{ msg }}</h1>
          {{ test }}
        </div>
      </template>
      
      <script lang="ts">
      import { defineComponent } from "vue";
      
      export default defineComponent({
        name: "HelloWorld",
        props: {
          msg: String
        },
        data() {
          return {
            test: "It's a test" as string
          }
        }
      });
      </script>
      

      【讨论】:

        猜你喜欢
        • 2021-09-01
        • 1970-01-01
        • 2019-11-14
        • 2017-12-04
        • 2018-10-21
        • 2018-05-16
        • 2019-04-19
        • 2019-01-02
        • 2021-07-19
        相关资源
        最近更新 更多