简体   繁体   中英

JS: How to mock a nested function in a jestJS unit test?

How do I mock a nested console.error in a jest unit test?

With my attempt (see below) I do get the error jest.fn() value must be a mock function or spy. Received: undefined jest.fn() value must be a mock function or spy. Received: undefined

Function

_onSubmit = (event) => {
  event.preventDefault()
  const { username, password } = this.state

  return this.props.createUserMutation({
    variables: { username, password }
  }).then(response => {
    const token = response.data.createUser.token
    if (token) {
      // do something
    } else {
      console.error('No token recieved')
    }
  })
}

Test

it('_onSubmit() should log error, if no token is recieved', (done) => {
  console['error'] = jest.fn()

  const createUserMutation = () => {
    return Promise.resolve({
      data: {
        createUser: { token: undefined }
      }
    })
  }
  const wrapper = shallow(<CreateAccount
    createUserMutation={createUserMutation}
  />)

  wrapper
    .update()
    .find(Form)
    .props()
    .onSubmit({ preventDefault: () => {} })
    .then(() => {
      expect(console.error()).toHaveBeenCalledWith('No token recieved')
      done()
    })
})

In this line, you're calling the function console.error instead of passing the function to expect, that's why you get undefined, since this fn won't return anything:

expect(console.error()).toHaveBeenCalledWith('No token recieved')

Instead of the result, you want to pass the function itself like so:

expect(console.error).toHaveBeenCalledWith('No token recieved')

Also, since you're trying to mock the global console function, you'll probably have to change your mock setup to something along the lines of:

global.console.error = jest.fn()

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