如何模拟组件的状态以进行单元测试?

时间:2018-11-09 17:08:19

标签: reactjs unit-testing jestjs enzyme

我正在使用酶,开玩笑,正弦波进行单元测试。我想模拟组件状态,并在组件得到渲染之前传递自定义状态。我该如何实现?

我的组件以某种初始状态开始:

constructor(props) {
   super(props);
   this.state = {
     sample: "hello"
   }
}

我想在渲染发生之前通过模拟假状态并在调用shallow()之前覆盖样本的值。

1 个答案:

答案 0 :(得分:-1)

直接在组件上调用setState吗?

不确定100%,但也许...

const myComponent = <MyComponent {...props} />
myComponent.setState({ ...mockState })

const myShallowRenderedComponent = shallow(myComponent)
const instance = myShallowRenderedComponent .instance()
expect(instance.state).toEqual(mockState)