reactjs - 单元测试: react context api with enzyme return an empty object

标签 reactjs unit-testing jestjs enzyme react-context

我第一次尝试使用 React context API 将信息从主组件传递到孙组件。

首先我创建了一个上下文

const MyContext = React.createContext({});

export default MyContext;

这里是设置上下文值的主要组件

import MyContext from "./MyContext.js";
import ParentComponent from "./ParentComponent.js";

function App() {
  return (
    <div>
      <MyContext.Provider value={{ foo: 12 }}>
        <ParentComponent />
      </MyContext.Provider>
    </div>
  );
}

父组件不关心上下文,只是创建孙组件

import ChildComponent from "./ChildComponent.js";

class ParentComponent extends Component {
  render() {
    return (
      <div>
        Parent
        <ChildComponent />
      </div>
    );
  }
}

export default ParentComponent;

这是读取上下文的子组件

import MyContext from "./MyContext.js";

class ChildComponent extends PureComponent {
  constructor() {
    super();
    this.state = {
      bar: 456
    };
  }

  render() {
    return (
      <div>
        <MyContext.Consumer>
          {({ foo }) => (
            <div>
              <h1>Hello I'm the ChildComponent</h1>
              <h2>Context value: {foo}</h2>
              <h2>State value: {this.state.bar}</h2>
              <button onClick={() => this.setState({ bar: foo })}>
                Click me
              </button>
            </div>
          )}
        </MyContext.Consumer>
      </div>
    );
  }
}

export default ChildComponent;

到目前为止没有问题。一切都按预期进行。 ChildComponent 已检索上下文值。

当我尝试用 jest/enzyme 测试它时,问题就出现了。我无法设置上下文

it("Should test the context value", () => {
  let wrapper = mount(<ChildComponent />, {
    context: { foo: 987 }
  });

  expect(wrapper.state("bar")).toEqual(456);
  expect(wrapper.context("foo")).toEqual(987);
});

最后一个期望失败并且上下文值为空对象。所以 foo 未定义

我在这里重现了这个问题: https://codesandbox.io/embed/x25yop4x5w?fontsize=14

感谢您的帮助

最佳答案

我用来测试需要安装在上下文提供程序树中的组件的方法是使用 wrappingComponentwrappingComponentProps options for mount .

这可以确保 mount(根组件)的返回值仍然是您要测试的组件(并且仍然支持仅适用于根组件的 API/选项,例如 setProps )。

mount(<MyComponent />, {
  wrappingComponent: MyContext.Provider,
  wrappingComponentProps: {
    value: { foo: 987 },
  },
})

关于reactjs - 单元测试: react context api with enzyme return an empty object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730219/

相关文章:

css - 如何用 React 覆盖默认的 MaterialUI 样式?

reactjs - 使用 react 钩子(Hook)检查组件是否已卸载?

javascript - Firefox 出现网络错误,而其他浏览器工作正常(ReactJS 应用程序)

ruby-on-rails - db :test:clone, db :test:clone_structure, db :test:load, 和 db :test:prepare? 有什么区别

java - 无法从我的 JUnit 测试中设置集群 Vert.x 环境

angular - 如何使用 Testing-Library、Jest 和 JSDOM 测试自定义元素/Web 组件?

javascript - 在 React useState Hook 中删除数组的第一个元素?

c++ - 从单元测试用例运行线程是一个好习惯吗?

javascript - module.exports Jest 测试中的多个函数

node.js - 由于拆卸不当导致 Jest 测试泄漏