jeudi 19 juillet 2018

How do I mock a react component property in jest which is instance of another class?

I want to test a react component which has instance of a service as a property. This service's method is called by a method in the component. I want to mock the service so its implementation is not my concern. Following is excerpts of my requirement:

// Component
export class SomeComponent extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  someService - new SomeService(arg1, arg2)

  handleClick() {
    // some transformations
    this.someService.someMethod()
  }

  render() {
    return <Button onClick={this.handleClick}>
      </Button>
  }
}

// test
describe.only('<SomeComponent/>', () => {
  it.only('should call handleClick when button is clicked', () => {
    const wrapper = shallow(<SomeComponent/>) // shallow render from enzyme
    const handleClick = jest.fn()
    const instance = wrapper.instance()
    instance.handleClick = handleClick
    wrapper.find(Button).simulate('click')
    expect(handleClick).toHaveBeenCalledTimes(1)
  })
})

But now I get the implementation details error of the services. How can I mock the service so that I can simply test the method of my Component?

Aucun commentaire:

Enregistrer un commentaire