Vue 测试实用程序 - setChecked() 不更新 v-model

Vue test utils - setChecked() not updating v-model

我正在为我在工作中制作的一些组件编写单元测试。我们正在使用 Mocha (TDD) 和 Chai 断言库。我有一个带有一些复选框的组件,并且从 vue-test-utils 对它们使用 setChecked() 方法没有按预期运行。我做了一个重现错误的小例子:

TestComponent.vue:

<template>
    <div>
        <input class="checkboxTest" type="checkbox" v-model="cbVal">
        <input class="inputTest" type="text" v-model="textVal">
    </div>
</template>

<script>
    define([], function() {
        return {
            data: function() {
                return {
                    cbVal: false,
                    textVal: ""
                }
            }
        }
    })
</script>

test.js:

suite("Random test", function() {
  var VueTest;
  var TestComponent;

  //Import the vue test utils library and TestComponent
  suiteSetup(function(done) {
    requirejs(
      ["vue-test-utils", "vuec!components/TestComponent"],
      function(VT, TC) {
        VueTest = VT;
        TestComponent = TC;
        done();
      }
    );
  });


  //This test passes
  test("fill in the input", function() {
    var wrapper = VueTest.mount(TestComponent);
    wrapper.find(".inputTest").setValue("Hello, world!");

    assert.equal(wrapper.vm.textVal, "Hello, world!");
  });

  //This one does not
  test("programatically check the box", function() {
    var wrapper = VueTest.mount(TestComponent);
    wrapper.find(".checkboxTest").setChecked(true);

    //Prints out AssertionError: expected false to equal true
    assert.equal(wrapper.vm.cbVal, true);
  });
});

TestComponent 中的 textVal 数据成员正在更改,但 cbVal 没有。任何人都可以解释为什么 setValue() 可以正常工作,但 setChecked() 不能吗?提前谢谢你。

我无法回答为什么它不起作用,但我可以告诉你,你的方法首先是不正确的。

您不应直接与 html 元素交互来设置它们的值。当您将 vue-model 设置为 cbVal 时,您应该与 cbVal.

进行交互

换句话说,将您的代码从 setChecked() 更改为 cbVal = true 以使其符合 Vue 希望您开发项目的方式。如果您不按照 Vue 希望的方式与您的代码交互,则无法保证 Vue 可以保持动态和反应。

我遇到了类似的问题,接受的答案并没有解决我的问题。我也不认为接受的答案是正确的,因为 setCheckedadded specifically to avoid having to manually set the values via the elements.

就我而言,我希望 Vue 对 v-model 更改做出反应并重绘。我尝试了 async 和许多其他方法,直到找到有效的方法:wrapper.vm.$forceUpdate().

我的工作代码如下所示:

wrapper.find("#someRadioButtonId").setChecked(true)
// manually force Vue to update
wrapper.vm.$forceUpdate() 
expect(wrapper.find("#someRadioButtonId").classes()).toContain("selected") // success!