javascript - 我应该如何正确触发更改事件以在单元测试中触发函数?

标签 javascript vue.js jestjs vue-test-utils

我有一个复选框组件,由于 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') 错误?

最佳答案

我的第二个测试设置为始终正确。我调用该函数

wrapper.vm.input()

然后断言它将被调用,这将永远是真的,所以这是一个糟糕的测试。

input.trigger('change')

...是正确的,这就是我拥有它的地方。这是我重构的测试:

  describe('when the checkbox state is changed', () => {
    let input
    beforeEach(() => {
      input = wrapper.find('input')
      jest.spyOn(wrapper.vm, 'input')
      jest.runAllTimers()
    })

    it('[positive] should emit an input event with the input\'s value', () => {
      input.trigger('change')
      expect(wrapper.emitted().input).toBeTruthy()
      expect(wrapper.emitted().input).toHaveLength(1)
      expect(wrapper.emitted().input[0]).toEqual([false])
    })
    it('[negative] should not emit an input event with the input\'s value', () => {
      input.trigger('input')
      expect(wrapper.emitted().input).toBeFalsy()
    })
  })

关于javascript - 我应该如何正确触发更改事件以在单元测试中触发函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55956467/

相关文章:

javascript - 语言切换器不应用新的区域设置

javascript - 如何防止 Vue Js 组件中事件监听器的多次调用?

javascript - 如何 Jest 测试这个正则表达式

facebook - 如何在测试 React.js 应用程序时从 Jest 获得测试覆盖率?

javascript - 字符串操作,删除标签

php - 输入类型提交与输入类型按钮

javascript - 我如何使用javascript代码隐藏div(使用php验证条件)

javascript - Node 错误发送后无法设置 header

django - Heroku:部署 Django Rest Framework + Vue

javascript - 使用 Promises 从 DynamoDB 异步检索数据