我正在尝试使用Jest as shown in the Airbnb doc在酶测试中传递上下文,但是上下文返回undefined
。我不确定我在做什么错。
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()
})
})
版本
React: 16.8.1
enzyme: 3.8.0
enzyme-adapter-react-16: 1.7.1
答案 0 :(得分:2)
似乎是open issue for enzyme的the new context api。作为解决方法,您可以设置静态contextTypes
:
App.contextTypes = {
name: PropTypes.string
};
然后,您可以根据需要操纵上下文:
shallow(<App />, {context: {name: "React is Simple"}}) // did mount
.setContext({ name: 'some new context'}); // did update
在您的应用中:
componentDidMount(){
console.log("Context in App", this.context)
}
componentDidUpdate() {
console.log(this.context);
}
希望有帮助。