Vue.js/nuxt.js - 测试组件内动态添加的方法

Vue.js/nuxt.js - test a dynamically added method inside a component

我正在尝试在我的一个组件中测试动态创建的方法,代码如下所示。

<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>

测试文件

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()
  })
}

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

尝试这样的事情:

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);
  });
});