如何在 Jest 中将数据作为上下文传递?

IT技术 javascript reactjs jestjs enzyme
2021-05-13 23:45:22

我正在尝试使用 Jest 在酶测试中传递上下文,如 Airbnb 文档中所示,但上下文正在返回undefined我不确定我在这里做错了什么。

应用程序.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;

应用程序.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
1个回答

对于新的上下文 api来说这似乎是酶的一个悬而未决的问题作为解决方法,您可以设置 static 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);
  }

希望能帮助到你。