Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a component method?

I'm simply trying to find out if a component method has been called after a store action, but I'm getting this error:

expect(jest.fn())[.not].toHaveBeenCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function bound mockConstructor]

This is my unit test:

describe('MyComponent.spec.js', () => {
  let methods = {
    setLocation: jest.fn()
    // more methods...
  }

  it('calls setLocation on undo/redo', () => {
    let wrapper = mount(MyComponent, {
      store,
      localVue,
      methods
    })

    store.dispatch('doUndo')
    expect(wrapper.vm.setLocation).toHaveBeenCalled()
  })
})

Not sure if this is a good practice or not, but I'm using the actual store and a local Vue instance.

like image 607
Nikolay Dyankov Avatar asked Apr 18 '19 10:04

Nikolay Dyankov


1 Answers

To verify the mocked method, use the actual mock variable itself (not via wrapper):

expect(methods.setLocation).toHaveBeenCalled()

Edit Verifying mocked method is called in Vue

like image 127
tony19 Avatar answered Sep 30 '22 06:09

tony19