测试setState的功能版本

问题描述 投票:2回答:1

假设我有一个像这样简单的React组件:

class Component extends React.Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }

  handleClick() {
    this.setState(prevState => {
      return { count: prevState.count + 1 }
    })
  }

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

我想测试当点击按钮时我的状态正确增加。这是我写的测试:

it('should increase state.count on click', () => {
  const component = shallow(<Component />)
  component.simulate('click')
  expect(component).toHaveState('count', 1) // Error, state.count is 0
})

问题是我不知道如何告诉Jest等待状态更新。我找到的一种方法是使用setTimeout,但它感觉hacky。

reactjs jestjs
1个回答
1
投票

You need to use component.update()

强制重新渲染。如果外部某些东西可能正在某处更新组件的状态,那么在检查渲染输出之前运行很有用。

  it('should increase state.count on click', () => {
    const component = shallow(<Component />)
    component.simulate('click')
    component.update()
    expect(component).toHaveState('count', 1)
  })
© www.soinside.com 2019 - 2024. All rights reserved.