我正在使用添加到上下文的方法,该方法在 componentDidMount()
生命周期方法中触发。
我应该能够通过为 Enzyme 的 shallow()
方法提供一个选项来 stub 上下文,但这并没有传递到我的组件。例如:
我的测试:
it('renders without crashing', () => {
const context = { dispatch: jest.fn() };
shallow(<MyComponent />, { context });
});
和我的组件:
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...
}
this.context
是一个对象,但它没有属性 - dispatch
始终未定义。
最佳答案
很遗憾,enzyme
尚不支持createContext
和contextType
。
可以看到它的进度here .
关于reactjs - 无法在 enzyme 测试中设置上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53711166/