Skip to content

Instantly share code, notes, and snippets.

@iannbing
Last active December 26, 2022 14:34
Show Gist options
  • Save iannbing/b6ac11079102bad4b81da68d610b9124 to your computer and use it in GitHub Desktop.
Save iannbing/b6ac11079102bad4b81da68d610b9124 to your computer and use it in GitHub Desktop.
How to mock Consumer in Jest
import React from "react";
import { render } from "@testing-library/react";
beforeEach(() => {
jest.resetModules();
});
const getComponentWithConsumer = (context = {}) => {
jest.doMock("../../Context", () => {
return { Consumer: props => props.children(context) };
});
return require("../ComponentWithConsumer").default;
};
describe("ComponentWithConsumer", () => {
it("should render with default values", () => {
const ComponentWithConsumer = getComponentWithConsumer({ foo: 'bar' });
const { getByText, getByTestId, container, asFragment } = render(
<ComponentWithConsumer>I am children</ComponentWithConsumer>
);
expect(container.firstChild).toMatchSnapshot();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment