简体   繁体   中英

Using Jest, how do I mock a method of a module used in a component to see how many times it's been called and with what values

I'm trying to mock a component which imports a history module to change the url. I just want to be able to mock the history.push method and check that it's been called and with what arguments after I've performed some user actions on it.

// MyForm
import { Component } from 'react'
import history from 'main/lib/history'

class MyForm extends Component {
  async componentDidMount() {
    try {
      const res = await fetch('BAD_URL')
      // do some stuff

    } catch (e) {
      history.push('error_page')
    }
  }

  render() {
    // ...
  }
}

export default MyForm
// Testing MyForm
import { render } from '@testing-library/react'
import MyForm from 'src/MyForm'

const mockPush = jest.fn((url) => {
  console.log('history pushing to this url:', url)
})

jest.mock('main/lib/history', () => {
  return jest.fn(() => {
    return {
      push: mockPush
    }
  })
})

test('history is pushed', () => {
  render(
    <MyForm />
  )
  expect(mockPush).toHaveBeenCalled() // 0 calls
})

It seems like any variations in implementation of this test I've tried either only show the console log and don't record the calls or cause errors.

As mentioned in the comments, used spyOn and checked the spy.mock.calls to check the arguments passed.

// Testing MyForm
import { render } from '@testing-library/react'
import MyForm from 'src/MyForm'
import history from 'main/lib/history'

jest.mock('main/lib/history', () => ({
  push: (url) => {
    console.log('history.push:', url)
  }
}))

test('history is pushed', () => {
  const spy = jest.spyOn(history, 'push')

  render(
    <MyForm />
  )

  expect(spy).toHaveBeenCalled() // true ... 1 call
  expect(spy.mock.calls[0][0]).toBe('error_page') // true
})

Not sure if there's a better way but this worked for me.

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