If your component has a custom model implementation, for example a custom checkbox, it would be nice to be able to easily mimic using this component with a v-model attribute, for example with a model option as a part of the mounting options.
Say that I want to mimic a usage like:
<template>
<my-checkbox value="c" v-model="myValues"></my-checkbox>
<template>
<script>
export default {
components: { MyCheckbox },
data() {
return {
myValues: ["a", "b"],
};
},
};
</script>
Then I would like to write my unit test like:
test("MyCheckbox", t => {
const myValues = ["a", "b"];
const wrapper = mount(MyCheckbox, {
model: myValues,
propsData: {
value: "c",
},
});
wrapper.element.checked = true;
wrapper.trigger('change');
t.deepEqual(model, ["a", "b", "c"]);
});
How about a setModel method?
At the moment with have a setComputed, setData, and setProps method. I think setModel would be in keeping with this API, rather than adding another mount option.
@eddyerburgh setModel is nice as well.
OK, if anyone wants to make a PR to implement this I'll review. Otherwise I'll look into adding at some point in the next week 馃檪
So I hadn't used v-model before. Now that I'm looking into it, I'm pretty sure you can achieve the same effect with setData. Can you show me an example for setModel where setData wouldn't work?
I'm closing this, but happy to reopen if someone provides a case where setData doesn't work
When use 'computed' function to deal with v-model, setData will not work.
Think about the example below:
computed: {
data: {
get() {
return this.value && this.value.name;
},
set(val) {
// do something with 'val'
this.$emit('input', {name: val});
}
},
}
How can I set the computed 'data' with setData ? So I do need the setModel method.
@Hquestion I got around this by adding a listener that updates the prop with setProps (how v-model works).
Computed prop:
innerValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('input', newValue);
},
},
Unit test mount options:
listeners: {
input: (newVal) => { // simulate v-model update
wrapper.setProps({ value: newVal });
}
}
I am pretty sure this works as it should atm. Closing.
Most helpful comment
How about a
setModelmethod?At the moment with have a
setComputed,setData, andsetPropsmethod. I thinksetModelwould be in keeping with this API, rather than adding another mount option.