首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用jest和酶测试react-context,其中context在构造函数中使用?

如何使用jest和酶测试react-context,其中context在构造函数中使用?
EN

Stack Overflow用户
提问于 2019-11-06 15:06:33
回答 2查看 3K关注 0票数 0

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

代码语言:javascript
复制
    class MyComponent extends Component {
      //constructor
      constructor(props, context) {
          super(props, context);

          const { testData } = this.context.storedData

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

我试图使用jest和酶框架测试react-context,但得到的错误如下:

代码语言:javascript
复制
  TypeError: Cannot read property 'testData ' of undefined

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

我已经尝试了大多数解决方案,但都不起作用。我正在寻找适合我情况的完美解决方案。

EN

回答 2

Stack Overflow用户

发布于 2019-11-06 16:27:09

从来没有使用过遗留环境,而且its doc page相当差。要测试依赖于上下文的组件,您必须传递该上下文,并且有很少的选择。

  1. 酶的mount()/shallow()提供了可用于传递上下文的second argument options。但我不确定它是否适用于旧版context

代码语言:javascript
复制
const wrapper = mount(<MyComponent />, { context: {storedData: {testData: 1} } });

  1. 使用额外的包装器来提供上下文:

代码语言:javascript
复制
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>) 

如果有可能更喜欢迁移到现代的上下文API,那就麻烦多了。

PS为什么你需要在构造函数中访问context?如果你在render()中使用它,你就不会担心"context已经更新,但render()仍然引用旧值“。

票数 0
EN

Stack Overflow用户

发布于 2021-01-05 00:04:27

实际上,传递带有上下文属性的选项将修复即使对于遗留上下文也是如此。

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

测试将是:

代码语言:javascript
复制
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();
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58724755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档