vuejs / vue-jest

Jest Vue transformer
MIT License
742 stars 159 forks source link

Test variables and functions of Vue 2.7 composition API component #521

Closed CazSaa closed 1 year ago

CazSaa commented 1 year ago

Hi all,

This may be a Vue issue and not Jest specific so let me know if that's the case but I thought I'd try asking here.

I'm updating a project to Vue 2.7 and I wanted to test the composition API. I created the following component:

<template>
  <div class="toggle">
    <div v-show="toggle">
      {{ text }}
      <slot :toggle="toggleSlots" name="first"></slot>
    </div>
    <div v-if="!toggle">
      <slot :toggle="toggleSlots" name="second"></slot>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const toggle = ref(true);

const text = ref('hi');

function toggleSlots() {
  toggle.value = !toggle.value;
}

setTimeout(() => {
  text.value = 'hii';
}, 1000);

</script>

and I wrote the following test:

import { createLocalVue, mount } from '@vue/test-utils';
import AppToggle from './toggle.vue';

const localVue = createLocalVue();

describe('Toggle', () => {
  it('should toggle the slots', async () => {
    const wrapper = mount(AppToggle, { localVue });

    expect(wrapper.vm.toggle).toBeTruthy(); // vm.toggle is undefined

    wrapper.vm.toggleSlots(); // vm.toggleSlots is undefined

    expect(wrapper.vm.toggle).toBeFalsy();
  });
});

If I write the component using the options API, test test passes, but with the composition API the test fails because the variables and functions are not defined on wrapper.vm. How can I access the variables and functions?

marlokessler commented 1 year ago

Hi there, we're experiencing the same issue. Also not sure whether it is an issue with vue2-jest or with vue. We're using Vue 2.7.14, vue2-jest v27.0.0. Would be glad for any help too!

CazSaa commented 1 year ago

@marlokessler I found the solution. See https://stackoverflow.com/a/74887122/14851412

marlokessler commented 1 year ago

Sadly, it does not work for me, but seems to be another issue. I opened another issue for that: https://github.com/vuejs/vue-jest/issues/525