如何正确触发更改事件以触发单元测试中的功能?

我有一个复选框组件,由于Safari的错误,我更改了


@input=input() to @change='input'

因为Safari没有输入事件。


复选框

<template>

  <div

    class="checkbox">

    <input

      ....

      @change="input">

  </div>

</template>


<script>

export default {

  ....

  methods: {

    input () {

      /**

       * Input event on change

       *

       * @event input

       * @type {Boolean}

       */

      this.$emit('input', this.$refs.checkbox.checked)

    }

  }

}

</script>

单元测试

  describe('...', () => {

    beforeEach(async () => {

      const input = wrapper.find('input')


      jest.spyOn(wrapper.vm, 'input')

      input.trigger('change') // told this is incorrect


      jest.runAllTimers()

    })


    it('[positive] should emit an input event with the input\'s value', () => {

      expect(wrapper.emitted().input).toBeTruthy()

      expect(wrapper.emitted().input).toHaveLength(1)

      expect(wrapper.emitted().input[0]).toEqual([false])

    })


    it('[positive] should call the input() method with the target value', () => {


     // this is wrong also, because the expectation will always be true

     wrapper.vm.input() 

     expect(wrapper.vm.input).toHaveBeenCalled()

    })

  })

我应该如何正确设置第二项测试?为什么在单元测试中input.trigger('change')是错误的?


慕勒3428872
浏览 197回答 1
1回答

守着一只汪

我的第二项测试设置为始终为真。我称这个功能wrapper.vm.input()然后断言它将被调用,这将是正确的,因此它是一个不好的测试。input.trigger('change')...是正确的,那正是我拥有的地方。这是我的重构测试:&nbsp; describe('when the checkbox state is changed', () => {&nbsp; &nbsp; let input&nbsp; &nbsp; beforeEach(() => {&nbsp; &nbsp; &nbsp; input = wrapper.find('input')&nbsp; &nbsp; &nbsp; jest.spyOn(wrapper.vm, 'input')&nbsp; &nbsp; &nbsp; jest.runAllTimers()&nbsp; &nbsp; })&nbsp; &nbsp; it('[positive] should emit an input event with the input\'s value', () => {&nbsp; &nbsp; &nbsp; input.trigger('change')&nbsp; &nbsp; &nbsp; expect(wrapper.emitted().input).toBeTruthy()&nbsp; &nbsp; &nbsp; expect(wrapper.emitted().input).toHaveLength(1)&nbsp; &nbsp; &nbsp; expect(wrapper.emitted().input[0]).toEqual([false])&nbsp; &nbsp; })&nbsp; &nbsp; it('[negative] should not emit an input event with the input\'s value', () => {&nbsp; &nbsp; &nbsp; input.trigger('input')&nbsp; &nbsp; &nbsp; expect(wrapper.emitted().input).toBeFalsy()&nbsp; &nbsp; })&nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript