0

I'm trying to make a test for dynamically created methods in one of my components the code goes like this.

<template>
  <div id="app">
    <div @click="executeDynamic('myCustomFunction')">Click me!</div>
  </div>
</template>

<script>
export default {
  name: "App",

  data () {
    return {
      // These contain all dynamic user functions
      userFuncs: {}
    }
  },

  created () {
    window.setTimeout(() => {
      this.$set(this.userFuncs, 'myCustomFunction', () => {
        console.log('whoohoo, it was added dynamically')
      })
    }, 2000)
  },

  methods: {
    executeDynamic (name) {
      if (this.userFuncs[name]) {
        this.userFuncs[name]()
      } else {
        console.warn(`${name} was not yet defined!`)
      }
    }
  }
};
</script>

test file

import WorkDateTime from "@/components/WorkDateTime.vue"
import Vue from "vue"

describe("WorkDateTime.vue", () => {
  it("allowedDatesFrom: today -> NG", () => {
    const that = { 
      $set: Vue.set
    }
    expect(WorkDateTime.data.userFuncs['myCustomFunction']).toBeTruthy()
  })
}

code pen https://codesandbox.io/s/vue-template-forked-ec7tg?file=/src/App.vue:0-662

1 Answer 1

1

Try something like that:

import { shallowMount } from '@vue/test-utils';
import WorkDateTime from '@/components/WorkDateTime.vue';

describe('WorkDateTime.vue', () => {
  it('userFuncs empty', () => {
    let wrapper = shallowMount(WorkDateTime);
    expect(wrapper.vm.userFuncs).toStrictEqual({});
  });

  it('userFuncs filled', async () => {
    let wrapper = shallowMount(WorkDateTime);
    let wait3Seconds = () => new Promise(resolve => setTimeout(() => resolve(), 3000));
    await wait3Seconds();
    expect(wrapper.vm.userFuncs['myCustomFunction']).toBeInstanceOf(Function);
  });
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.