如何在Jest中将数据作为上下文传递? [英] How to pass data as context in Jest?
本文介绍了如何在Jest中将数据作为上下文传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Jest在酶测试中传递上下文,显示在Airbnb文档中,但上下文返回undefined
.我不确定我在做什么错.
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()
})
})
版本
React: 16.8.1
enzyme: 3.8.0
enzyme-adapter-react-16: 1.7.1
推荐答案
似乎是 新上下文api 的酶的公开问题.解决方法是,您可以设置静态 contextTypes
:
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
在您的应用中:
componentDidMount(){
console.log("Context in App", this.context)
}
componentDidUpdate() {
console.log(this.context);
}
希望有帮助.
这篇关于如何在Jest中将数据作为上下文传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文