我有一个确认模式组件,该组件会在回调中返回true / false,但我无法使其正常工作。尝试了诸如jest.fn().mockReturnValue(true)
之类的各种事情。
为了测试通过事件总线返回回调的组件,是否有任何提示/建议?
components / confirmModal.vue
<template lang="pug">
transition(name='fade')
#swConfirm.confirm-modal-overlay(v-if='isShow', @click='handleClickOverlay')
transition(name='zoom')
.confirm-modal-container(v-if='isShow')
span.confirm-modal-text-grid(@click.stop='')
h5.confirm-modal-title(v-if='dialog.title') {{ dialog.title }}
p.confirm-modal-text(v-if='dialog.message') {{ dialog.message }}
.confirm-modal-btn-grid(:class='{ isMono: dialog.isMono }')
button.confirm-modal-btn.left(v-if='!dialog.isMono', @click.stop='e => handleClickButton(false)')
| {{ dialog.button.no || "Cancel" }}
button.confirm-modal-btn(@click.stop='e => handleClickButton(true)')
| {{ dialog.button.yes || "OK" }}
</template>
<script>
import Vue from 'vue'
import { events } from '../plugins/confirm-modal'
Vue.directive('focus', {
inserted: function(el) {
el.focus()
}
})
const Component = {
name: 'confirmModal',
data() {
return {
isShow: false,
dialog: {
title: '',
message: '',
button: {},
isMono: false
},
params: {}
}
},
methods: {
resetState() {
this.dialog = {
title: '',
message: '',
button: {},
isMono: false,
callback: () => {}
}
},
handleClickButton(confirm) {
this.isShow = false
if (this.params.callback) {
this.params.callback(confirm)
}
},
handleClickOverlay() {
this.isShow = false
},
open(params) {
this.resetState()
this.params = params
this.isShow = true
Object.entries(params).forEach(param => {
if (typeof param[1] == typeof this.dialog[param[0]]) {
this.dialog[param[0]] = param[1]
}
})
}
},
mounted() {
events.$on('open', this.open)
}
}
export default Component
</script>
plugins / confirm-modal.js(我需要使用它来使组件在整个应用程序中均可访问)
import confirmModal from "~/components/confirmModal.vue"
import Vue from "vue"
export const events = new Vue({
name: 'confirm-modal'
})
export default (ctx, inject) => {
Vue.component('confirm-modal', confirmModal)
const confirm = params => {
events.$emit('open', params)
}
confirm.close = () => {
events.$emit('close')
}
ctx.$confirm = confirm
inject("confirm", confirm)
}
我在组件上调用它的方式是这样的
reset() {
this.$confirm({
message: "Reset the form ?",
callback: async (confirm) => {
if (confirm) {
localStorage.removeItem("formWorks")
}
}
})
},
我正在尝试像下面这样测试,但没有运气
beforeEach(async () => {
wrapper = shallowMount(New, {
mocks: {
$confirm: jest.fn().mockReturnValue(true)
}
})
})
it("resets formWorks)", async () => {
wrapper.vm.reset()
})
答案 0 :(得分:1)
您将要使用mockImplementation
:
beforeEach(async () => {
wrapper = shallowMount(New, {
mocks: {
$confirm: jest.fn().mockImplementation(({ callback }) => callback(true))
}
})
})
我希望您会在异步回调中遇到一些问题,这是需要注意的。