本文介绍了如何在 Jest 中将数据作为上下文传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Jest 在酶测试中传递上下文,asAirbnb 文档中显示,但上下文返回 undefined
.我不确定我在这里做错了什么.
App.js
class App 扩展组件{componentWillMount(){console.log("Context in App", this.context)//运行测试用例时未定义}使成为(){返回(<div>示例应用程序
)}}导出默认应用程序;
App.test.js
从'react'导入React;从酶"导入{浅};从'./App'导入应用程序;describe('App 测试用例', () => {让包装;让 AppContext = {name: "React 很简单"};beforeEach(() => {包装器 = 浅(,{上下文:AppContext})})test('应该通过渲染组件而不会崩溃', () => {期望(包装器).toMatchSnapshot()})})
版本
反应:16.8.1酶:3.8.0酶适配器反应 16:1.7.1
解决方案
这似乎是一个新上下文 api 的酶的开放问题.作为解决方法,您可以设置静态 contextTypes
:
App.contextTypes = {名称:PropTypes.string};
然后你可以随意操作上下文:
shallow(, {context: {name: "React is Simple"}})//确实挂载了.setContext({ name: '一些新的上下文'});//有更新
在您的应用中:
componentDidMount(){console.log("应用中的上下文", this.context)}componentDidUpdate() {控制台日志(this.context);}
希望有帮助.
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
解决方案
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.
这篇关于如何在 Jest 中将数据作为上下文传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!