首页 文章

状态变化后测试反应组分

提问于
浏览
0

如何测试以下组件?

import React from "react";

    class ModuleLoader extends React.Component {
            state = {
                    Module: null
            };
            componentDidMount() {
                    this.props
                            .Module()
                            .then(loaded => {
                                    this.setState({ Module: loaded.default });
                            })
            }
            render() {
                    if (this.state.error) {
                            return "error";
                    }
                    if (!this.state.Module) {
                            return "loading";
                    }
                    return <this.state.Module {...this.props} />;
            }
    }

    export default ModuleLoader;

Prop Module是通过动态导入返回promise的函数 . 解析并加载该导入后,它将返回一个反应组件,该组件应存储在状态并呈现 . 那么测试看起来应该让组件解析网络请求加载它,显示它并在渲染之后检查断言?

我希望能够检查渲染组件上的状态是否发生了变化 . 但是我不能在文档中为这样的东西提供资金 .

我正在使用 MeteorMochaEnzyme . 如果无法使用 Enzyme 测试组件,我可以切换到替代方案 .

谢谢 .

2 回答

  • -1

    解决方案是正确使用承诺和 await .

    it('renders', async () => {
      const props = {
        Module: () =>
          Promise.resolve({
            default: () => <span>Im loaded!</span>,
          }),
      };
      const component = mount(<ModuleLoader {...props} />);
      expect(component).toMatchSnapshot();
      await Promise.resolve(); // tick so promises resolve
      expect(component.update()).toMatchSnapshot();
    });
    

    资料来源:https://gist.github.com/danielhusar/8df72f5677ec69cb9774c1d5c561c56a

  • 0

    为什么不能用酶实现你想要的行为?你的componentDidMount()是不是用浅渲染调用的?如果是这样,您可以尝试完全渲染(https://github.com/airbnb/enzyme#full-dom-rendering)或者创建一个从componentDidMount()调用的辅助方法,但也可以在单元测试中手动调用 . 然后在等待该方法之后,您可以测试呈现的组件是否包含 Module . 所以,我认为你有两个选项来测试这个组件呈现 Module .

相关问题