Reactjs 如何模拟组件';单元测试的状态是什么?
我正在使用酵素、jest、sinon进行单元测试。我想模拟一个组件状态,并在组件得到渲染之前传递一个自定义状态。我怎样才能做到这一点 我的组件以一些初始状态开始:Reactjs 如何模拟组件';单元测试的状态是什么?,reactjs,unit-testing,jestjs,enzyme,Reactjs,Unit Testing,Jestjs,Enzyme,我正在使用酵素、jest、sinon进行单元测试。我想模拟一个组件状态,并在组件得到渲染之前传递一个自定义状态。我怎样才能做到这一点 我的组件以一些初始状态开始: constructor(props) { super(props); this.state = { sample: "hello" } } 我想在模拟假状态和调用shallow()之前,在渲染之前覆盖sample的值。直接在组件上调用setState 不是100%确定,但也许 const myCompon
constructor(props) {
super(props);
this.state = {
sample: "hello"
}
}
我想在模拟假状态和调用shallow()之前,在渲染之前覆盖sample的值。直接在组件上调用setState 不是100%确定,但也许
const myComponent = <MyComponent {...props} />
myComponent.setState({ ...mockState })
const myShallowRenderedComponent = shallow(myComponent)
const instance = myShallowRenderedComponent .instance()
expect(instance.state).toEqual(mockState)
const myComponent=
myComponent.setState({…mockState})
const myShallowRenderedComponent=shallow(myComponent)
const instance=myShallowRenderedComponent.instance()
expect(instance.state).toEqual(mockState)
我想在模拟假状态和调用shallow()之前,在渲染之前覆盖sample的值-为什么?此解决方案不起作用,因为myComponent
变量是元素
并且不公开setState
方法myComponent
不是myComponent
的实例。它是对要创建的组件的描述。在React呈现/初始化元素之前,实际上没有React.Component
。请参阅失败示例:。有关差异的更多信息,请访问:。