Search code examples
vuejs2vue-test-utils

vue-test-utils how to use trigger's options


I want to test el-button if it can change to the correct view by $router,but I am confused weather the trigger supportted cause i find this in its document

The trigger method takes an optional options object. The properties in the options object are added to the Event.

Note that target cannot be added in the options object.

const wrapper = mount(MyButton)
wrapper.trigger('click', { 
    button: 0
})

but failed and i get this info

TypeError: Cannot set property type of [object Event] which has only a getter

  65 |     // expect(mockFn).toBeCalled
  66 |     // expect(mockFn).toBeCalledTimes(1)
  67 |     wrapper.find(ElementUI.Button).trigger('click', {
     |                                    ^
  68 |       id: 1,
  69 |       type: 'view'
  70 |     })

vue file

<el-button
    plain
    type="primary"
    @click="changeView(-1, 'edit')">
    newPicture
</el-button>

js

changeView(id, type) {
    if (type === 'view') {
       this.$router.push({ path: './detail', query: { id, type }})
     } else if (type === 'edit') {
       this.$router.push({ path: './edit', query: { id, type }})
     }
},

And I want to write a test file for this button

   ...
    it('add button click', () => {
        const mockFn = jest.fn()
        wrapper.setMethods({
            changeView: mockFn
        })
        wrapper.find(ElementUI.Button).trigger('click', {
            id: 1,
            type: 'view'
        })
        wrapper.update()
        expect(mockFn).toBeCalled
        console.log(wrapper.vm.$route.path)
   })
  ...

How can I fix this?


Solution

  • the options your passing are js $event properties. here's a list of them: https://www.w3schools.com/jsref/obj_event.asp

    when you trigger that click event, the changeView will be called, with the parameters you passed to it(-1 and 'edit'). they are not event properties and you dont pass them as options. so your test whould look like:

      it('add button click', () => {
            const mockFn = jest.fn()
            wrapper.setMethods({
                changeView: mockFn
            })
            wrapper.find(ElementUI.Button).trigger('click');
            wrapper.update();
            expect(mockFn).toBeCalledWith(-1,'edit');
       })