0

How do I test if blur() is called using jest?

This is my function:

blurOnEnter (event) {
  if (event.keyCode === 13 && !event.shiftKey) event.target.blur()
}

And this is how I would test it, but I don't know how to handle my expect statement:

it('blurOnEnter() should blur target input field', () => {
  const blur = jest.fn()
  wrapper = shallow(<Component />)
  wrapper.instance().blurOnEnter({
    keyCode: 13,
    target: { blur }
  })
  expect(blur.calls.length).toBe(1) // TypeError: Cannot read property 'length' of undefined
})

Why do I get the TypeError Cannot read property 'length' of undefined

user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

1

How about:

it('blurOnEnter() should blur target input field', () => {
  const blur = jest.fn()
  wrapper = shallow(<Component />)
  wrapper.instance().blurOnEnter({
    keyCode: 13,
    target: { "blur": blur } // see here!
  })
  expect(blur.mock.calls.length).toBe(1) // and here
})

According to jest mocking docs at (http://facebook.github.io/jest/docs/en/mock-functions.html#content) jest mocks have mock property while your original code didn't use that.

teroi
  • 1,087
  • 10
  • 19