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



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

测试组件.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((却不行吗?提前谢谢。

我遇到了类似的问题,接受的答案并没有解决我的问题。我认为接受的答案也不正确,因为添加setChecked是为了避免必须通过元素手动设置值。

在我的情况下,我希望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!

我无法回答为什么它不起作用,但我可以告诉你,你的方法一开始就不正确。

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

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

最新更新