How to test defineModel with vitest?
I've write a Toast.vue component:
<template>
<div v-if="show">
{{ text }}
</div>
</template>
<script setup lang="ts">
interface ToastType {
text: string
time?: number
}
const props = defineProps<ToastType>()
const show = defineModel({default: false })
watch(show, () => {
if (show.value) {
setTimeout(() => {
show.value = false
}, props.time || 2000)
}
})
</script>
and test file:
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { shallowMount } from '@vue/test-utils'
import Toast from '../Toast.vue'
const props = {
text: 'hello toast',
time: 2500,
modelValue: false
}
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
vi.useFakeTimers()
describe('Toast.vue', () => {
it('Toast Props', async () => {
const wrapper = shallowMount(Toast, {
propsData: props
})
await wrapper.setProps({
modelValue: true
})
vi.runAllTimers()
await wrapper.vm.$nextTick()
expect(wrapper.emitted()).toHaveProperty('update:modelValue')
expect(wrapper.emitted('update:modelValue')).toHaveLength(1)
// error AssertionError: expected true to be false // Object.is equality
expect(wrapper.vm.modelValue).toBe(false)
})
})
I really do not know how to do, please know the small partners to guide, thank you very much.
For vue:"^3.4" changing the model value directly seems to work:
// inside CheckboxLikeComponent
const model = defineModel<boolean>({
required: true,
set: (value) => {
state.touched = true;
return value;
},
});
type TFoo = {
comp: ReturnType<
typeof withComponent<
typeof CheckboxLikeComponent,
ICheckboxLikeComponentState,
{
model: boolean;
}
>
>;
};
beforeEach<TFoo>((context) => {
context.comp= withComponent(CheckboxLikeComponent, {
props: {
name: 'test',
modelValue: false,
},
});
});
it<TFoo>('element is updated by changing the v-model', async ({
comp,
}) => {
const checkboxElement = comp.wrapper.find('input').element;
expect(checkboxElement.checked).toBeFalsy();
comp.wrapper.vm.model = true;
await nextTick();
expect(checkboxElement.checked).toBeTruthy();
expect(comp.state.value?.touched).toBeTruthy();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With