【问题标题】:How to mock React Context for testing component with jest如何模拟 React Context 以用玩笑测试组件
【发布时间】:2020-09-23 05:28:05
【问题描述】:

我想测试组件是否在渲染函数中渲染。组件封装在 Consumer 内部:

const TestComponent = () => (
  <div>
<ItemsContext.Consumer>
            {(value) => (
              <Autos
                autoEnabled={value.autoEnabled}
              />
            )}
          </ItemsContext.Consumer>
  </div>
);

我在上层组件中设置了上下文:

const AutosWrapper = () => (

      <ItemsContext.Provider value={{ autoEnabled: false, sourcesEnabled: true }}>
        <TestComponent/>
      </ItemsContext.Provider>

)

我的测试如下:

import ItemsContext from '../ItemsContext';

describe('<TestComponent /> Component render', () => {

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<TestComponent {...props} />);
  });

  describe('<TestComponent /> rendering', () => {


    test('should render child components in <TestComponent /> component', () => {
      const autoContextWrapper = wrapper.find(ItemsContext.Consumer).at(0)
        .renderProp('children')();

      expect(autoContextWrapper.find(Autos).length).toEqual(1);
    });

  });
});

但是当我运行这个测试时,我有以下错误 - TypeError: Cannot read property 'autoEnabled' of undefined 我无法理解如何将默认值传递给上下文或模拟它们。我尝试了这样的变体但没有成功:

ItemsContext.Consumer = jest.fn((props) => props.children({ autoEnabled: false }));

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    您必须使用提供者包装您的组件,以便消费者可以访问上下文。这特别有用,因为这使您能够更改上下文并根据给定的上下文值进行断言。

    例子:

    import ItemsContext from '../ItemsContext';
    
    describe('<TestComponent /> Component render', () => {
      describe('<TestComponent /> rendering', () => {
        test('should render child components in <SearchResult /> component', () => {
          const wrapper = shallow((
            <ItemsContext.Provider value={{ autoEnabled: true, sourcesEnabled: true }}>
              <TestComponent />
            </ItemsContext.Provider>
          ));
    
          const autoContextWrapper = wrapper
            .find(ItemsContext.Consumer)
            .at(0)
            .renderProp('children')();
    
          expect(autoContextWrapper.find(Topics).length).toEqual(1);
        });
      });
    });
    

    【讨论】:

    • 我有一个错误 - 方法“renderProp”应该在 1 个节点上运行。找到了 0 个。在调试方法中,我根本看不到该组件呈现
    • 我将dive() 添加到浅层渲染以修复错误“renderProp”应该在1 个节点上运行。找到了 0 ',但现在我在测试过程中出现初始错误 'TypeError: Cannot read property 'autoEnabled' of undefined'
    • 抱歉回复晚了,是否可以创建一个可以重现此错误的代码沙箱?我从经验中知道,让 Enzyme 使用包装的组件(例如提供程序)可能会很棘手。 Material-UI 在他们的测试中使用了以下函数:github.com/mui-org/material-ui/blob/master/packages/material-ui/…
    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 2021-06-16
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多