React 16.6 introduced the ability to consume data from context without using the Consumer component directly. This helps to cut down on unnecessary nesting in your components’ JSX, making them easier to read. In this lesson we’ll see how to replace a Consumer by using the contextType property.
FYI: The 'before' code for this lesson is here if you need it.
Hi Dave, How would you go about testing a class component that uses the static contextType field, instead of the render props method.
For instance:
class MyButton extends React.Component {
static contextType = UserContext
render() {
const { isConnected } = this.context
return(
<button>{isConnected() ? 'Disconnect' : 'Connect'}</button>
)
}
}
Currently trying to figure out if something like this would work
import { render } from 'react-testing-library'
import MyButton from '../mybutton'
test('it should change on connect', () => {
//Set Context like so?
MyButton.contextType = MockContext
const { container } = render(<MyButton/>)
})
That seems like it should work. Does it? If not, maybe you could mock the context at the module level: https://jestjs.io/docs/en/es6-class-mocks