Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何模拟组件';单元测试的状态是什么?_Reactjs_Unit Testing_Jestjs_Enzyme - Fatal编程技术网

Reactjs 如何模拟组件';单元测试的状态是什么?

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

我正在使用酵素、jest、sinon进行单元测试。我想模拟一个组件状态,并在组件得到渲染之前传递一个自定义状态。我怎样才能做到这一点

我的组件以一些初始状态开始:

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
。请参阅失败示例:。有关差异的更多信息,请访问:。