-
-
Save jmacqueen/6b2fd375decbba96223f13a1b5b20eb7 to your computer and use it in GitHub Desktop.
React Context.Consumer mocking
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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); | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment