How to test a react component that is dependent on useContext hook?
Asked Answered
U

8

116

I have a component that uses useContext and then its output is dependent on the value in the context. A simple example:

import React, { useContext } from 'react';

const MyComponent = () => {
  const name = useContext(NameContext);

  return <div>{name}</div>;
};

When testing this component with the shallow renderer from react and jest snapshots. How can I change the value of NameContext?

Unrepair answered 14/2, 2019 at 13:40 Comment(6)
you may just wrap your component with <NameContext.Provider>: github.com/facebook/react/issues/7905Supercolumnar
That doesn't seem to work with shallow rendering because then it won't render the internals of my component. When I tried that I got a snapshot like: <NameContext.Provider value={'Paul'}><MyComponent/></NameContext.Provider> instead of <div>Paul</div>Unrepair
yes, here .dive() is made forSupercolumnar
.dive() is from enzym but there is nothing similar for the react shallow renderer.Unrepair
yes, you're right, missed that partSupercolumnar
Any suggestion for #59332396 ?Marika
D
79

In general, using hooks shouldn't change testing strategy much. The bigger issue here actually isn't the hook, but the use of context, which complicates things a bit.

There's a number of ways to make this work, but only approach I've found that works with 'react-test-renderer/shallow' is to inject a mock hook:

import ShallowRenderer from 'react-test-renderer/shallow';

let realUseContext;
let useContextMock;
// Setup mock
beforeEach(() => {
    realUseContext = React.useContext;
    useContextMock = React.useContext = jest.fn();
});
// Cleanup mock
afterEach(() => {
    React.useContext = realUseContext;
});

test("mock hook", () => {
    useContextMock.mockReturnValue("Test Value");
    const element = new ShallowRenderer().render(
        <MyComponent />
    );
    expect(element.props.children).toBe('Test Value');
});

This is a bit dirty, though, and implementation-specific, so if you're able to compromise on the use of the shallow renderer, there's a few other options available:

Non-shallow render

If you're not shallow rendering, you can just wrap the component in a context provider to inject the value you want:

import TestRenderer from 'react-test-renderer';

test("non-shallow render", () => {
    const element = new TestRenderer.create(
        <NameContext.Provider value="Provided Value">
            <MyComponent />
        </NameContext.Provider>
    );
    expect(element.root.findByType("div").children).toEqual(['Provided Value']);
});

(Disclaimer: this should work, but when I test it, I'm hitting an error which I think is an issue in my setup)

Shallow render with Enzyme and Dive

As @skyboyer commented, enzyme's shallow renderer supports .dive allowing you to deeply renderer a part of an otherwise shallow rendered component:

import { shallow } from "./enzyme";

test("enzyme dive", () => {
    const TestComponent = () => (
        <NameContext.Provider value="Provided Value">
            <MyComponent />
        </NameContext.Provider>
    );
    const element = shallow(<TestComponent />);
    expect(element.find(MyComponent).dive().text()).toBe("Provided Value");
});

Use ReactDOM

Finally, the Hooks FAQ has an example of testing hooks with ReactDOM, which works as well. Naturally, using ReactDOM means this is also a deep render, not shallow.

let container;
beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
});

afterEach(() => {
    document.body.removeChild(container);
    container = null;
});

test("with ReactDOM", () => {
    act(() => {
        ReactDOM.render((
            <NameContext.Provider value="Provided Value">
                <MyComponent />
            </NameContext.Provider>
        ), container);
    });

    expect(container.textContent).toBe("Provided Value");
});
Depriest answered 5/3, 2019 at 23:30 Comment(5)
I like the mock idea. It didn't cross my mind. Not as elegant as the other approaches but more elegant than the approaches I tried. I love the deep function idea, I hope they will bring it to react shallow renderer at some point. Thanks for your answer!Unrepair
I am facing a challenge when using Enzyme, I exactly followed the mock idea you have shown but the problem is by the time I check my condition component is not rendered with context value. Note : I update my component with context value in useEffect.Lucilius
What if the value is an object that contains a property and a function.Transfix
What if MyComponent contains a child?Transfix
I am getting the following error - Cannot assign to 'useContext' because it is a read-only property.Audrey
U
22

I tried to use Enzyme + .dive, but when diving, it does not recognize the context props, it gets the default ones. Actually, it is a known issue by the Enzyme team. Meanwhile, I came up with a simpler solution which consists in creating a custom hook just to return useContext with your context and mocking the return of this custom hook on the test:

AppContext.js - Creates the context.

import React, { useContext } from 'react';

export const useAppContext = () => useContext(AppContext);

const defaultValues = { color: 'green' };
const AppContext = React.createContext(defaultValues);

export default AppContext;

App.js — Providing the context

import React from 'react';
import AppContext from './AppContext';
import Hello from './Hello';

export default function App() {
  return (
    <AppContext.Provider value={{ color: 'red' }}>
      <Hello />
    </AppContext.Provider>
  );
}

Hello.js - Consuming the context

import React from 'react';
import { useAppContext } from './AppContext';

const Hello = props => {
  const { color } = useAppContext();
  return <h1 style={{ color: color }}>Hello {color}!</h1>;
};

export default Hello;

Hello.test.js - Testing the useContext with Enzyme shallow

import React from 'react';
import { shallow } from 'enzyme';
import * as AppContext from './AppContext';

import Hello from './Hello';

describe('<Hello />', () => {
  test('it should mock the context', () => {
    const contextValues = { color: 'orange' };
    jest
      .spyOn(AppContext, 'useAppContext')
      .mockImplementation(() => contextValues);
    const wrapper = shallow(<Hello />);
    const h1 = wrapper.find('h1');

    expect(h1.text()).toBe('Hello orange!');
  });
});

Check the full Medium article out https://medium.com/7shifts-engineering-blog/testing-usecontext-react-hook-with-enzyme-shallow-da062140fc83

Uhl answered 30/5, 2019 at 14:39 Comment(1)
I have followed same example. i see actual default values are mocked every time i run the test. Mock values not rendered, can you please let me know what is missing.Dissatisfaction
A
16

Or if you're testing your component in isolation without mounting the parent components you can simply mocking useContext:

jest.mock('react', () => {
  const ActualReact = jest.requireActual('react')
  return {
    ...ActualReact,
    useContext: () => ({ }), // what you want to return when useContext get fired goes here
  }
})
Abode answered 15/10, 2019 at 15:7 Comment(2)
Warning: this replaces useContext everywhere and so breaks any part of the thing under test that also uses useContext, e.g. styled-components. Alex Andrade's answer will allow you to isolate which uses of useContext you'd like to mock.Proteus
@Proteus you can check the value.displayName to see if it's from StylesContext, ThemeContext in case of material ui if you have useContext: value => {...}, and return accordingly or leave the original function.Farland
O
6

To complete the above accepted answer, for non-shallow rendering, I slightly tweaked the code to simply surround my component with the context

import { mount } from 'enzyme';
import NameContext from './NameContext';

test("non-shallow render", () => {
    const dummyValue = {
      name: 'abcd',
      customizeName: jest.fn(),
      ...
    }; 
    const wrapper = mount(
        <NameContext.Provider value={dummyValue}>
            <MyComponent />
        </NameContext.Provider>
    );

    // then use  
    wrapper.find('...').simulate('change', ...);
    ...
    expect(wrapper.find('...')).to...;
});
Outboard answered 9/5, 2020 at 9:10 Comment(3)
The accepted answer contains the exaple for non-shallow renderingAttitude
Hi, if you look carefully it's not quite the same (uses TestRenderer) and gave me an error when I tried it. Hence why I shared this.Outboard
I implemented this and it's not working for me. wrapper returns as undefined =/ codesandbox.io/s/react-usecontext-jest-test-9r93g?file=/src/…Dilisio
T
5

Old post but if it helps someone this is how I got it to work

import * as React from 'react';
import { shallow } from 'enzyme';

describe('MyComponent', () => {
  it('should useContext mock and shallow render a div tag', () => {
    jest.spyOn(React, 'useContext').mockImplementation(() => ({
      name: 'this is a mock context return value'
    }));

    const myComponent = shallow(
      <MyComponent
        props={props}
      />).dive();

    expect(myComponent).toMatchSnapShot();
  });
});
Tisatisane answered 14/9, 2020 at 21:24 Comment(0)
I
2

In the test, you need to wrap the component with the "Context Provider". Here is the simple example.

The DisplayInfo component is dependent on UserContext.

import React, { useContext } from 'react';
import { UserContext } from './contexts/UserContextProvider';

export const DisplayInfo = () => {
 const { userInfo } = useContext(UserContext);

 const dispUserInfo = () => {
   return userInfo.map((user, i) => {
    return (
     <div key={i}>
      <h1> Name: { user.name } </h1>
      <h1> Email: { user.email } </h1>
     </div>
    )
  });
 }

 return(
  <>
   <h1 data-testid="user-info"> USER INFORMATION </h1>
   { userInfo && dispUserInfo() })
  </>
 }

export default DisplayInfo;

Here is the User Context Provider.

import React, {useState, createContext} from 'react';

export const UserContext = createContex();

const UserContextProvider = () => {
 const [userInfo, setUserInfo] = useState([]);

 const updateUserInfo = () => {
  setUserInfo([...userInfo, newData]);
 }

 const values = {
  userInfo,
  updateUserInfo
 }

 return(
  <UserContext.Provider = vlaue={values}>
   {props.children}
  </UserContext.Provider>
 )
}

export default UserContextProvider;

To test the "DisplayInfo" compoent, it might also be needed to use the "MemoryRouter" from "react-router-dom". Here is the example -

import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { DisplayInfo } from "./DisplayInfo";
import UserContextProvider from "./contexts/UserContextProvider";
import { MemoryRouter } from "react-router-dom";

describe("DisplayInfo", () => {
 describe("layout", () => {
  it("has header of user info", () => {
   render(
    <UserContextProvider>
     <DisplayInfo />
    </UserContextProvider>,
    { wrapper: MemoryRouter }
   );
   let header = screen.getByTestId('user-info');
   expect(header).toHaveTextContent(/user information/i)
  });
 });
});
Imbecile answered 27/2, 2022 at 9:9 Comment(0)
P
1

What I did is test if useContext was used. In my case, useContext returns function called dispatch.

In the component I have:

const dispatch = useContext(...);

and then inside onChange method:

dispatch({ type: 'edit', payload: { value: e.target.value, name: e.target.name } });

So inside test at the begining:

  const dispatch = jest.fn();
  React.useContext = (() => dispatch) as <T>(context: React.Context<T>) => T;

and then:

  it('calls function when change address input', () => {
   const input = component.find('[name="address"]');
   input.simulate('change', { target: { value: '123', name: 'address' } });

   expect(dispatch).toHaveBeenCalledTimes(1);
  });
Pteryla answered 22/10, 2020 at 9:58 Comment(0)
X
0

I've found a palatable way to mock context where I can elegantly inject my own values for testing.

import React, {
  createContext,
  useContext,
  useState,
  useEffect,
} from "react";

const initState = {
  data: [],
};

export const ThingsContext = createContext(initState);

export const useThings = () => {
  const data = useContext(ThingsContext);
  if (data === undefined) {
    throw new Error("useThing must be used within a ThingsProvider");
  }
  return data;
};

export const ThingsProvider = ({
  children,
  value: { state: oState } = {},
}) => {
  const[data, setData] = useState();

  useEffect(() => {
    const getData = async () => {
      const data = await // api call;
      setData(data);
    }
    getData();
  }, []);

  return (
    <ThingsContext.Provider
      value={{ state: oState ?? state }}
    >
      {children}
    </ThingsContext.Provider>
  );
};

This way I could override the actual state and test whatever values I desire.

import React from "react";
import { render, screen } from "@testing-library/react";

import { ThingsProvider } from "store/things";
import Things from "./Things";

const defaultValue = {
  state: ["pot", "kettle", "black"],
};

const renderComponent = (children, value=defaultValue) => {
  const el = render(
      <ThingsProvider value={value ?? defaultValue} >{children}</ThingsProvider>
  );
  screen.debug();
  return el;
};

describe("<Things />", () => {
  it("should render thing", () => {
    renderComponent(<Things />);
  });
  expect(screen.getByText("pot")).toBeInTheDocument();

  it("should not render thing", () => {
    renderComponent(<Things />, {state: []});
  });
  expect(screen.queryByText("pot")).not.toBeInTheDocument();
});
Xanthin answered 18/1, 2023 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.