Irith
Irith

Reputation: 123

Vue Composition API + Jest

I'm trying out Vue3 composition api and I'm having some issue writing tests for it.

I wrote new component(MyComponent) in my app using composition api. MyComponent uses another component that was written with Options api (MyOtherComponent). Everything works fine if I run the app but when I write the Unit Test (using Jest) I start having issues where 'this' is not recognised anymore and evaluated as undefined.

Please see the code snippets below (take it as pseudo-code)...

Anyone knows how I can possibly fix or work around this issue?

MyOtherComponent.vue

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
  <div></div>
<template>

<script lang="ts">

export default class MyOtherComponent extends Vue {
  public doSomething() {
    this.$log('MyOtherComponent is doing something!');
  }
}

</script>

MyComponent.vue

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div @click="onClick">
    <my-other-component ref="myOtherComponent" />
  </div>
</template>

<script lang="ts">
export default {
  name: 'MyComponent',
  components: ['MyOtherComponent'],
  setup() {
    const myOtherComponent = ref<MyOtherComponent | null>(null);
    const state = ref<Boolean>(false);
    
    function onClick() {
      myOtherComponent.value.doSomething().then(() => {
        state.value = true;
      });
    }
    
    return {
      onClick
    }
  }
}
</script>

MyComponent.test.ts

fdescribe('Testing MyComponent', () => {
  let wrapper: Wrapper<MyComponent>;
  
  beforeEach(() => {
    const localVue = createLocalVue();
    
    localVue.use(VueCompositionApi);
    wrapper = mount(MyComponent, { localVue };
  })

  afterEach(() => {
        wrapper.destroy();
    });

  test('post click test', async() => {
        expect(wrapper.vm.$data.state).toBeFalsy();
        await wrapper.find('div:first-child').trigger('click');
        expect(wrapper.vm.$data.state).toBeTruthy();
    });
})

Upvotes: 0

Views: 2666

Answers (1)

Matt
Matt

Reputation: 10312

In Vue 3 there is no global Vue instance, so there's no need for createLocalVue.

Your beforeEach would change:

import { mount } from '@vue/test-utils';

// …

beforeEach(() => {
    wrapper = mount(MyComponent);
});

// …

Upvotes: 1

Related Questions