我有这个简单的代码,它使用新的getDerivedStateFromProps
生命周期:
static getDerivedStateFromProps(nextProps: Props, prevState: State) {
if (nextProps.value !== prevState.value) {
console.log('hello');
return {
value: nextProps.value
};
}
return null;
}
这是测试:
it('should call getDerivedStateFromProps', () => {
const instance = shallow(mockComponent());
instance.setProps({ value: 'test2' });
expect(instance.state.value).toEqual('test2');
});
但我有这个错误,但我知道这是因为 console.log() 而调用的。
Expected value to equal:
"test2"
Received:
undefined
我该如何正确测试getDerivedStateFromProps
?
我在用着:
react: 16.4
react-Dom: 16.4
enzyme-adapter-react-16: 1.1.1
react-test-renderer: 16.4.1
它是一个没有依赖性的静态函数。我认为你可以像其他功能一样单独测试它:
const givenProps = {...};
const givenState = {...};
const result = MyComponent.getDerivedStateFromProps(givenProps, givenState);
expect(result).toEqual({
...
})
我认为这是一个有效的方法,因为getDerivedStateFromProps https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops不应该包含任何副作用并且是纯粹的 - 这意味着 - 给定相同的输入,它将产生相同的输出。而且因为组件的实例在这里没有相关性,所以创建一个组件只会测试内部的反应。
这也类似于测试 redux 减速器的方式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)