Skip to content

Instantly share code, notes, and snippets.

@dndhm
Last active March 30, 2023 09:17
Show Gist options
  • Select an option

  • Save dndhm/27ce047f4688f9d7968a495c96e31958 to your computer and use it in GitHub Desktop.

Select an option

Save dndhm/27ce047f4688f9d7968a495c96e31958 to your computer and use it in GitHub Desktop.
React Context.Consumer mocking
import React, { Component } from 'react';
import FruitContext from './FruitContext';
import FruityComponent from './FruityComponent';
export class App extends Component {
state = {
fruit: 'apple',
}
render() {
return (
<FruitContext.Provider value={this.state.fruit}>
<FruityComponent />
</FruitContext.Provider>
);
}
}
import { createContext } from 'react';
export default createContext('banana');
import React from 'react';
import FruitContext from './FruitContext';
import FruityHeader from './FruityHeader';
export default () => (
<FruitContext.Consumer>
{fruit => (
<FruityHeader>{fruit}</FruityHeader>
)}
</FruitContext.Consumer>
);
import React from 'react';
import { mount } from 'enzyme';
import FruityComponent from './FruityComponent';
const mockContext = jest.fn();
jest.mock('./FruitContext', () => ({
Consumer: ({ children }) => children(mockContext()),
}));
describe('FruityComponent', () => {
beforeEach(() => {
mockContext.mockReset();
});
['banana', 'apple', 'kumquat'].map(fruit =>
test(`should pass ${fruit} context to FruityHeader`, () => {
mockContext.mockReturnValue(fruit);
const fruityHeader = mount(<FruityComponent />).find('FruityHeader');
expect(fruityHeader.prop('children')).toEqual(fruit);
}));
});
@dndhm

dndhm commented Jun 19, 2018

Copy link
Copy Markdown
Author

This is obviously an inappropriate use case for contexts, but should provide an easy to understand example for mocking context consumers in our tests.

@alycrys

alycrys commented Jul 20, 2018

Copy link
Copy Markdown

How would you test AppWithContext.js?

@mackness

mackness commented Oct 28, 2018

Copy link
Copy Markdown

Downside is you would have to have the jest.mock and mockContext.mockReset in every test that required mock context. Why not globally mock the module (https://jestjs.io/docs/en/manual-mocks)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment