我要测试特定的发射名称称为?

时间:2018-06-29 06:49:16

标签: javascript vue.js karma-jasmine sinon

我使用karma对vue进行了编码单元测试。我可以通过以下代码检查emit is trigger(called)

test.spec.js

let stub = sinon.spy(vm, "$emit")
vm.save()
expect(stub.called).toBeTruthy()

test.vue

methods: {
  save() {
    this.$emit('edit-field', true);
    this.close()
  },
  close() {}
}

但是我想检查specific emit触发器,我尝试了如下操作,但不起作用...

let stub = sinon.spy(vm, "$emit('edit-field')") //getting error 
stub = sinon.spy(vm, "$emit::edit-field") //getting error also
vm.save()
expect(stub.called).toBeTruthy()

2 个答案:

答案 0 :(得分:1)

  • 检查发射名称

it(' -> edit function', () => {
    let stub = sinon.stub(vm, '$emit')
    stub.callsFake(name => {
     expect(name).toBe('edit-field')
    })
    vm.close()
  })

答案 1 :(得分:0)

使用官方@vue/test-utils,您可以执行以下操作:

import { shallowMount } from '@vue/test-utils'

const wrapper = shallowMount(Component)
wrapper.vm.save();
expect(wrapper.emitted()['edit-field'].length).toBe(1);
expect(wrapper.emitted()['edit-field'][0]).toEqual([true]);

来自docs