问题
I am trying to pass the context in an Enzyme test using Jest, as shown in the Airbnb doc, but the context is returning undefined
. I am not sure what I am doing wrong here.
App.js
class App extends Component{
componentWillMount(){
console.log("Context in App", this.context) // getting undefined when running test case
}
render(){
return(
<div>
Sample Application
</div>
)
}
}
export default App;
App.test.js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
describe('App test cases', () => {
let wrapper;
let AppContext = {name: "React is Simple"};
beforeEach(() => {
wrapper = shallow(<App />, {context: AppContext })
})
test('should pass render the component without crashing', () => {
expect(wrapper).toMatchSnapshot()
})
})
Versions
React: 16.8.1
enzyme: 3.8.0
enzyme-adapter-react-16: 1.7.1
回答1:
It seems to be an open issue for enzyme for the new context api. As a workaround you can set up static contextTypes:
App.contextTypes = {
name: PropTypes.string
};
Then you can manipulate the context as you wish:
shallow(<App />, {context: {name: "React is Simple"}}) // did mount
.setContext({ name: 'some new context'}); // did update
And in your App:
componentDidMount(){
console.log("Context in App", this.context)
}
componentDidUpdate() {
console.log(this.context);
}
Hope it helps.
来源:https://stackoverflow.com/questions/55293154/how-to-pass-data-as-context-in-jest