Vue 3 Vitest -输入时测试v模型

4xrmg8kj  于 2023-02-09  发布在  Vue.js
关注(0)|答案(1)|浏览(198)

我正在尝试使用v模型属性为BaseInput创建测试。预期组件将发出更改的输入。当我在Vitest框架中更新输入时,似乎没有触发发出。

    • 组件**
<template>
  <label v-if="label">{{ label }}</label>
  <input
    v-bind="$attrs"
    :value="modelValue"
    :placeholder="label"
    @input="$emit('update:modelValue', $event.target.value)"
    class="field"
  />
</template>

<script>
export default {
  props: {
    label: {
      type: String,
      default: "",
    },
    modelValue: {
      type: [String, Number],
      default: "",
    },
  },
};
</script>
    • 测试**
import { describe, it, expect, beforeEach } from "vitest";
import { mount } from "@vue/test-utils";
import BaseInput from "@/components/base/BaseInput.vue";

describe("BaseInput", () => {
  let wrapper

  beforeEach(() => {
    wrapper = mount(BaseInput, {
      propsData: {
        label: 'Test Label',
        modelValue: 'Test Value'
      }
    })
  })

  it('emits input value when changed', async () => {
    // Assert input value gets the new value
    await wrapper.find('input').setValue('New Test Value')
    expect(wrapper.find('input').element.value).toBe('New Test Value')

    // Assert input event is emitted
    await wrapper.vm.$nextTick()
    expect(wrapper.emitted().input).toBeTruthy() //this fails
  })

});
    • 结果:**在设置值时,没有从输入发出任何内容。

如何设置输入以证明组件发出输入组件的新值?

qoefvg9y

qoefvg9y1#

这实际上在Vue测试实用程序示例中作为示例进行了讨论:https://test-utils.vuejs.org/guide/advanced/v-model.html#a-simple-example
以下是在Vue 3中测试v模型的方法

import { describe, it, expect, beforeEach } from "vitest";
import { mount } from "@vue/test-utils";
import BaseInput from "@/components/base/BaseInput.vue";

describe("BaseInput", () => {
  let wrapper;

  beforeEach(() => {
    wrapper = mount(BaseInput, {
      propsData: {
        label: "Test Label",
        modelValue: "Test Value",
        "onUpdate:modelValue": (e) => wrapper.setProps({ modelValue: e }),
      },
    });
  });

  it("emits input value when changed", async () => {
    // Assert input value gets the new value
    await wrapper.find("input").setValue("New Test Value");
    expect(wrapper.props("modelValue")).toBe("New Test Value");
  });
});

相关问题