首页 > 解决方案 > 如何在 nuxt.js 中编写 vuebootstrap 的 $bvModal.msgBoxConfirm 的测试用例

问题描述

如何为此组件编写测试用例,如何为此编写单元用例,附加到 dom 现在可能在这种情况下工作,

如何为此组件编写测试用例,如何为此编写单元用例,附加到 dom 现在可能在这种情况下工作,

<template>
  <div>
    <div class="mb-2">
     <b-button @click="showMsgBoxOne">Simple msgBoxConfirm</b-button>
     Return value: {{ String(boxOne) }}
    </div>
    <div class="mb-1">
     <b-button @click="showMsgBoxTwo">msgBoxConfirm with options</b-button>
     Return value: {{ String(boxTwo) }}
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        boxOne: '',
        boxTwo: ''
      }
    },
    methods: {
      showMsgBoxOne() {
        this.boxOne = ''
        this.$bvModal.msgBoxConfirm('Are you sure?')
          .then(value => {
            this.boxOne = value
          })
          .catch(err => {
            // An error occurred
          })
      },
      showMsgBoxTwo() {
        this.boxTwo = ''
        this.$bvModal.msgBoxConfirm('Please confirm that you want to delete everything.', {
          title: 'Please Confirm',
          size: 'sm',
          buttonSize: 'sm',
          okVariant: 'danger',
          okTitle: 'YES',
          cancelTitle: 'NO',
          footerClass: 'p-2',
          hideHeaderClose: false,
          centered: true
        })
          .then(value => {
            this.boxTwo = value
          })
          .catch(err => {
            // An error occurred
          })
      }
    }
  }
</script>

标签: vue.jsnuxt.jsbootstrap-vue

解决方案


async showMsgBoxTwo() {
    this.boxTwo = ''
    try {
        const res = await this.$bvModal.msgBoxConfirm('Please confirm that you want to delete everything.', {
            title: 'Please Confirm',
            size: 'sm',
            buttonSize: 'sm',
            okVariant: 'danger',
            okTitle: 'YES',
            cancelTitle: 'NO',
            footerClass: 'p-2',
            hideHeaderClose: false,
            centered: true
        })
        this.boxTwo = res
    } catch (e) {
        // error
    }
}

然后

it('test', () => {
    const wrapper = shallowMount(Component, {
        store,
        localVue,
        propsData: {},
    })
    const spy = jest.spyOn(wrapper.vm.$bvModal, 'msgBoxConfirm')
    spy.mockImplementation(() => Promise.resolve(some value))
    wrapper.vm.showMsgBoxTwo()
    wrapper.vm.$nextTick(() => {
        expect(spy).toHaveBeenCalled()
    })
})

推荐阅读