无法阅读属性' contextTypes'未定义的,反应路由器测试

时间:2017-11-20 20:17:10

标签: javascript reactjs testing enzyme react-router-v4

我想测试用于验证用户登录状态的函数。但我总是得到错误

public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}  

实际上我使用TypeError: Cannot read property 'contextTypes' of undefined at createMountWrapper (node_modules/enzyme-adapter-utils/build/createMountWrapper.js:147:37) at Object.render (node_modules/enzyme-adapter-react-15/build/ReactFifteenAdapter.js:159:88) at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:98:16) at mount (node_modules/enzyme/build/mount.js:19:10) at renderedMount (src/hoc/AuthenticationHOC.test.js:20:32) at Object.it (src/hoc/AuthenticationHOC.test.js:25:21) at new Promise (<anonymous>) at Promise.resolve.then.el (node_modules/p-map/index.js:46:16) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7) 为react-routers构建一个伪道具,并希望在页面更改时测试createRouterContext属性的更改。以下是用于验证用户登录状态的函数。

this.props.history

这是我创建的当前测试文件

export function authenticationRequired(WrappedComponent) {
  return class extends React.Component {
    componentWillReceiveProps(nextProps) {
      // if the user has no 'user_id' attribute, assume the user is logged out
      if (!nextProps.user_id) {
        this.props.history.replace('/login')
      }
    }

    render() {
      // return the given component as is
      return <WrappedComponent {...this.props} />
    }
  }
}

我错过了什么吗?任何人都可以帮我解决这个测试问题吗?

1 个答案:

答案 0 :(得分:0)

由于您的测试组件不是本机react-router组件,因此在测试之前还应声明向其添加静态contextTypes属性,如here所述:

const context = createRouterContext();
const childContextTypes = {
  router: React.PropTypes.object
}
const renderedMount = () => {
  return mount( authenticationRequired(<WrappedComponent {...props} />), { context, childContextTypes } )
}