context.js: This file just creates the context with the new Context API.
import { createContext } from 'react'
const Context = createContext({})
export { Context }
provider.js: This is a wrapper that meant to declare the elements that should be passed to the context.
import { Context } from './context'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
class Provider extends Component {
constructor(props) {
super(props)
}
getContext(props) {
return Object.assign({}, {
a: 1,
b: 2,
c: 3
})
}
render() {
return (
<Context.Provider value={this.getContext(this.props)}>
{this.props.children}
</Context.Provider>
)
}
}
Provider.propTypes = {
children: PropTypes.node
}
export default Provider
dummy.js: This component uses the context.
import { Context } from '~/utils/context'
import React, { Component } from 'react'
class Dummy extends Component {
render() {
const { a, b, c } = this.context
return (
<ul>
<li>{a}</li>
<li>{b}</li>
<li>{c}</li>
</ul>
)
}
}
Dummy.contextType = Context
export default Dummy
dummy.spec.js: This is the test that should run.
import Dummy from '../dummy'
const context = {
a: 1,
b: 2,
c: 3
}
describe('dummy', () => {
it('context should be defined', () => {
const wrapper = shallow(<Dummy />, { context })
expect(wrapper.context()).toEqual(context)
})
})
This code works when running the app as i'm receiving the context. But when testing the context is just an empty object.
Note: When moving Dummy.contextType = Context
to
Dummy.contextTypes = {
a: PropTypes.number,
...
}
the context is correctly defined. But as i'm using the new API this is not possible. I also test with mount
but with the same result. Also i tried to upgrade enzyme and the adapter to the latest version without success.
The context should be declared on the component and in the test when running wrapper.context()
| library | version
| ------------------- | -------
| enzyme | ^3.9.0
| react | ^16.8.2
| react-dom | ^16.8.2
| react-test-rendered | N/A
| adapter (below) |
I saw in the issue https://github.com/airbnb/enzyme/issues/1553 that this feature is not supported yet. Closing this issue.