使用Jest和酶测试getDerivedStateFromPro

使用Jest和酶测试getDerivedStateFromPro

本文介绍了如何使用Jest和酶测试getDerivedStateFromProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用新的 getDerivedStateFromProps 生命周期的简单代码:

I have this simple code that is using the new getDerivedStateFromProps lifecycle:

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()而正在调用。 / p>

But I have this error but I know that is calling because of the 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


推荐答案

这是一个没有依赖关系的静态函数。我认为您可以像其他所有功能一样单独对其进行测试:

It's a static function with no dependency. I think you can test it in isolation like every other function:

const givenProps = {...};
const givenState = {...};
const result = MyComponent.getDerivedStateFromProps(givenProps, givenState);

expect(result).toEqual({
  ...
})

我认为这是一种有效的方法,因为不应包含任何副作用,并且应是纯净的-这意味着-给定相同的输入,它将产生相同的输出。而且由于组件实例与此处无关,因此创建一个实例只会对内部产生反应,因此不会进行任何测试。

I think it is a valid approach because of getDerivedStateFromProps should not contain any side-effects and be pure - which means - given the same input it will produce the same output. And because the instance of a component has no relevance here creating one would test nothing but react internals.

这也将与您测试redux reducer的方式类似。

This would be also similar to how you would test a redux reducer.

这篇关于如何使用Jest和酶测试getDerivedStateFromProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:00