Last active
March 30, 2023 09:17
-
-
Save dndhm/27ce047f4688f9d7968a495c96e31958 to your computer and use it in GitHub Desktop.
React Context.Consumer mocking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext } from 'react'; | |
export default createContext('banana'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import FruitContext from './FruitContext'; | |
import FruityHeader from './FruityHeader'; | |
export default () => ( | |
<FruitContext.Consumer> | |
{fruit => ( | |
<FruityHeader>{fruit}</FruityHeader> | |
)} | |
</FruitContext.Consumer> | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
})); | |
}); |
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
How would you test AppWithContext.js?