rick1
rick1

Reputation: 946

How to mock React Context for testing component with jest

I want to test if component renders inside render function. Component is wrapped inside Consumer:

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

I set context in the upper component:

const AutosWrapper = () => (

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

)

My test is as follows:

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);
    });

  });
});

but when I run this test, I have following error - TypeError: Cannot read property 'autoEnabled' of undefined I cannot understand how to pass default values to the context or mock them. I tried such a variant but without success:

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

Upvotes: 2

Views: 7064

Answers (1)

Chris
Chris

Reputation: 6631

You will have to wrap your component with the provider so that the consumer can access the context. This is especially useful as this enables you to change the context and do assertions based on the given context value.

Example:

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);
    });
  });
});

Upvotes: 1

Related Questions