简体   繁体   中英

How to test that blur() has been called?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM