How to pass data as context in Jest?

南楼画角 提交于 2019-12-12 14:40:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!