David Gomez
David Gomez

Reputation: 2772

Test inner functions with Jest's snapshots

I want to know if there is a way to test inner component functions that are not in the props using Jest's snapshots?

For this component:

class Comp extends Component {
  state = {
    ...
  }

  handleSomething = () => {
    doSomething()
  }

  render() {
    return (
      <div>
        { this.props.foo }
        <ChildComp onClick={ this.handleSomething } />
      </div>
    )
  }
}
export default Comp

I'm trying to do something like this:

test('Comp', () => {
  const component = renderer.create(
    <Comp foo="bar" />
  )

  let tree = component.toJSON()
  expect(tree).toMatchSnapshot()

  tree.props.handleSomething() // TypeError: tree.props.handleSomething is not a function
  tree = component.toJSON()
  expect(tree).toMatchSnapshot()
})

But I'm getting the type error because handleSomething is not a component prop.

Is there any way to test this function using the snapshots?

Upvotes: 0

Views: 497

Answers (1)

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110892

You could use enzyme to render the component and trigger the click on ChildComp.

import { shallow } from 'enzyme'

test('Comp', () => {
  const component = shallow(
    <Comp foo="bar" />
  )

  component.find('ChildComp').simulate('click')
  expect(component).toMatchSnapshot()
})

Note that you will need enzyme-to-json to make the snapshot feature work

Upvotes: 1

Related Questions