Nikolay Dyankov
Nikolay Dyankov

Reputation: 7214

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.

Upvotes: 5

Views: 7814

Answers (1)

tony19
tony19

Reputation: 138196

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

Upvotes: 6

Related Questions