在React浅酶-Jest测试用例上传递上下文

时间:2019-03-20 08:34:58

标签: javascript reactjs enzyme

如何传递上下文并使用辅助方法提取数据?

请参见以下代码段:

import AppContext from '../../context/AppContext'
import extractDatta from '../../helper';

class App extends Component{
  static contextType = AppContext

  componentWillMount(){
   const resolvedData = extractData("/home",this.context)
  }

 render(){
   return(
  )
 }

}

helper / index.js:

const extractData = (path, context) => {
  // getting context as undefined 
}

App.test.js:

describe('App test suites', () => {
  let wrapper;
  let appContext;
  beforeEach(() => {
    appContext = {name: "Application"}
    wrapper = shallow(<Supplier />, { appContext })
  })
  it('Should render the App Component', () => {
    expect(wrapper).toMatchSnapshot();
  })
})

任何帮助表示赞赏:)

2 个答案:

答案 0 :(得分:0)

因此,这是我的棘手解决方法,而酶团队正在努力完成对[https://github.com/airbnb/enzyme/issues/1553](React 16的支持)。我在组件类上提供了旧版contextTypes,允许根据文档传递上下文。

import PropTypes from "prop-types";

describe('App test suites', () => {
  let wrapper;
  let appContext;
  beforeEach(() => {
    appContext = {name: "Application"}

    // Hack in the legacy context API just for tests. You'll get a warning, but it 
    // ought to work...
    Supplier.contextTypes = {
      name: PropTypes.string
    }

    wrapper = shallow(<Supplier />, { appContext })
  })

  it('Should render the App Component', () => {
    expect(wrapper).toMatchSnapshot();
  })
})

答案 1 :(得分:0)

这可能无济于事。但是,您是否不应该通过带有上下文参数名称的Option对象而不是appContext来传递?

wrapper = shallow(<Supplier />, { context: appContext })