Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test defineModel use vitest?

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.

like image 388
toimc Avatar asked Dec 05 '25 23:12

toimc


1 Answers

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();
});
like image 127
luQ Avatar answered Dec 07 '25 16:12

luQ