无法在酶测试中设置上下文

J_P*_*J_P 2 reactjs jestjs enzyme

我正在使用添加到上下文的方法,该方法在componentDidMount()生命周期方法中触发。

我应该能够通过为 Enzyme 的shallow()方法提供一个选项来存根上下文,但这不会传递到我的组件。例如:

我的测试:

it('renders without crashing', () => {
  const context = { dispatch: jest.fn() };

  shallow(<MyComponent />, { context });
});
Run Code Online (Sandbox Code Playgroud)

和我的组件:

import React, { Component } from 'react';
import { Consumer, Context } from '../../context';

class MyComponent extends Component {
  static contextType = Context;

  componentDidMount() {
    const { dispatch } = this.context; // dispatch is `undefined`

    dispatch({ type: 'BLAH', payload: 'blah' });
  }

  etc...

}
Run Code Online (Sandbox Code Playgroud)

this.context是一个对象,但它没有属性 -dispatch始终是未定义的。

小智 5

不幸的是,还不enzyme支持。createContextcontextType

您可以在这里看到它的进展。