我有一个BaseCheckbox组件,该组件使用“值”道具呈现一个复选框。当我单击标记时,组件将发出event.target.checked。使用笑话进行测试时,event.target.checked不会更改,并且会发出与prop相同的值。在浏览器中运行时,event.target.checked每次单击时都会正确更改,并且每次发出与属性prop相反的值(我通过在BaseCheckbox.vue中添加console.log进行检查)。
<template>
<div class="custom-checkbox">
<div v-if="value" class="checkmark"></div>
<input :checked="value" type="checkbox" @change="onChange" />
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
required: true
}
},
methods: {
onChange(event) {
console.log(event.target.checked);
this.$emit("input", event.target.checked);
}
}
};
</script>
it("should emit 'input' event with value payload", () => {
wrapper.setProps({ value: true });
expect(wrapper.vm.$props.value).toEqual(true);
wrapper.find("input").trigger("change");
expect(wrapper.emitted().input[0]).toEqual([false]);
})
期望:发出与prop值相反的值
实际:在开玩笑中:发出与值prop相同的值,浏览器:发出与值prop相反的值
FAIL tests/components/baseComponents/BaseCheckbox.spec.js
BaseCheckbox
✓ should show checkmark when value is true (6ms)
✓ should not show checkmark when value is false (3ms)
✕ should emit 'input' event with value payload (84ms)
● BaseCheckbox › should emit 'input' event with value payload
expect(received).toEqual(expected)
Expected value to equal:
[false]
Received:
[true]
Difference:
- Expected
+ Received
Array [
- false,
+ true,
]
23 | expect(wrapper.vm.$props.value).toEqual(true);
24 | wrapper.find("input").trigger("change");
> 25 | expect(wrapper.emitted().input[0]).toEqual([false]);
| ^
26 | })
27 | })
28 |
at Object.toEqual (tests/components/baseComponents/BaseCheckbox.spec.js:25:44)
console.log src/components/baseComponents/BaseCheckbox.vue:18
true
Test Suites: 1 failed, 1 total
Tests: 1 failed, 2 passed, 3 total
Snapshots: 0 total
Time: 5.435s
答案 0 :(得分:0)
我自己弄清楚了。 Vue-Test-Utils为该确切用例提供了功能。
https://vue-test-utils.vuejs.org/api/wrapper/#setchecked
it("should emit 'input' event with value payload", () => {
wrapper.setProps({ value: true });
wrapper.find("input").setChecked(false);
expect(wrapper.emitted().input[0]).toEqual([false]);
})