Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 开玩笑';已装入';for click事件仅在两次单击后才起作用?(测试Vue应用程序)_Vue.js_Jestjs_Vue Test Utils - Fatal编程技术网

Vue.js 开玩笑';已装入';for click事件仅在两次单击后才起作用?(测试Vue应用程序)

Vue.js 开玩笑';已装入';for click事件仅在两次单击后才起作用?(测试Vue应用程序),vue.js,jestjs,vue-test-utils,Vue.js,Jestjs,Vue Test Utils,一个简单的组件: <template> <div> <p> {{ count }} </p> <button @click="increment" data-test="increment">Increment</button> </div> </template> <script> export default { data ()

一个简单的组件:

<template>
  <div>
    <p>
      {{ count }}
    </p>
    <button @click="increment" data-test="increment">Increment</button>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        count: 0
      }
    },
    methods: {
      increment () {
        this.count++
      }
    }
  }
</script>
如您所见,我触发了两次单击incrementButton

在第一次调用之后,如果我测试是否调用了“increment”方法,它将返回false。然而,计数确实是递增的。在第二次调用之后,它注册它实际上被调用了(如果我测试它被调用了多少次,它会断言它被调用了一次,即使计数是2,显然已经增加了两次)


关于Jest/Vue的工作原理,我遗漏了什么?

您需要使用Vue测试Utils方法:

const wrapper=mount(Foo)
const clickMethodStub=sinon.stub()
wrapper.setMethods({clickMethod:clickMethodStub})
wrapper.find('button')。trigger('click'))
expect(clickMethodStub.called).toBe(true)
它在您的示例中不起作用的原因是,您分派单击的元素具有组件实例化时创建的原始处理程序


它在两次调用
trigger
后工作,因为初始调用会导致重新渲染,并且修补的元素已更新其处理程序,以使用添加到实例中的存根方法。

值得指出的是,
setMethods
现在已被弃用。
import TestExperiment from '@/components/TestExperiment'
import { createLocalVue, shallowMount } from '@vue/test-utils'

const localVue = createLocalVue()

describe('testexperiment.test.js', () => {
  const cmp = shallowMount(TestExperiment, {
    localVue
  })

  const increment = jest.spyOn(cmp.vm, 'increment')
  const incrementButton= cmp.find('[data-test="increment"]')

  test('clicking increment button calls increent', () => {

    expect(incrementButton.exists()).toBe(true)

    incrementButton.trigger('click')

    // Checking call here fails:
    // expect(increment).toHaveBeenCalled()

    // Function was still obviously called
    expect(cmp.vm.count).toBe(1)

    incrementButton.trigger('click')

    // Checking call here passes:
    expect(increment).toHaveBeenCalled()
  })

})