使用 Jest 的快照测试内部函数

大卫戈麦斯

我想知道是否有一种方法可以使用 Jest 的快照来测试不在 props 中的内部组件功能?

对于这个组件:

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

  handleSomething = () => {
    doSomething()
  }

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

我正在尝试做这样的事情:

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()
})

但我收到类型错误,因为handleSomething它不是组件道具。

有没有办法使用快照来测试这个功能?

安德烈亚斯·科伯勒

您可以使用来渲染组件并触发对ChildComp.

import { shallow } from 'enzyme'

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

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

请注意,您需要酶到 json才能使快照功能正常工作

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章