如何在构造函数内部使用上下文的情况下使用玩笑和酶来测试react-context?

我正在使用react-context保存数据并访问构造函数中的数据,如下所示:

    class MyComponent extends Component {
      //constructor
      constructor(props,context) {
          super(props,context);

          const { testData } = this.context.storedData

          this.state={
          //maintained states
          }
      }
      //constructor ends
    }

我正在尝试使用笑话和酶框架测试react-context,但收到如下错误:

  TypeError: Cannot read property 'testData ' of undefined

  25 |   constructor(props,context) {
  26 |     super(props,context);
> 27 |     const { testData  } = this.context.storedData
     |             ^

我已经尝试了大多数解决方案,但是没有任何效果。我正在寻找适合我情况的完美解决方案。

cuterose 回答:如何在构造函数内部使用上下文的情况下使用玩笑和酶来测试react-context?

从未使用过Legacy Context,并且its doc page很差。要测试依赖于上下文的组件,您必须传递该上下文,并且选项很少。

  1. 酶的mount() / shallow()提供了second argument options,可用于传递上下文。但是我不确定它是否适用于旧版上下文
const wrapper = mount(<MyComponent />,{ context: {storedData: {testData: 1} } });
  1. 使用其他包装器提供上下文:
function createWrapperForContext (contextData) {
  return class Wrapper extends React.Component {
    getChildContext() {
      return contextData;
    }

    render() {
      return this.props.children;
    }
  };
}
....
const ContextWrapper = createWrapperForContext(testData);
const elementWrapper = mount(<ContextWrapper><YourComponent /></ContextWrapper>) 

如果有可能更喜欢使用现代的Context API,那就少了很多。

PS为什么您需要在构造函数中访问context?如果您在render()中使用它,则不必担心“上下文已更新,但是render()仍引用旧值”。

,

事实上,即使对于旧的上下文,传递带有上下文属性的选项也能解决问题。

假设我们有 color 上下文 https://reactjs.org/docs/legacy-context.html

测试将是:

import { shallow,ShallowWrapper } from 'enzyme';
import React from 'react';

describe('MyComponent',() => {
  let component = ShallowWrapper<MyComponentProps>;

  // This will test the default color value
  it('should render with default context',() => {
    component = shallow(<MyComponent {...props}/>);

    expect(component).toMatchSnapshot();
  });
  // testing with different context
  it('should render with context',() => {
    component = shallow(<MyComponent {...props} />,{
      context: {
        color: 'red',// you still give it the default value.
      },});

    component.setContext({ color: 'purple' });
    component.instance().forceUpdate(); // you could call also render from instance
    expect(component).toMatchSnapshot();
  });
});

本文链接:https://www.f2er.com/3154362.html

大家都在问