如何解决Vue.js / nuxt.js-测试组件内部动态添加的方法
我正在尝试对其中一个组件中动态创建的方法进行测试,代码如下所示。
<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);
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。