reactjs - 无法在 enzyme 测试中设置上下文

标签 reactjs jestjs enzyme

我正在使用添加到上下文的方法,该方法在 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 尚不支持createContextcontextType

可以看到它的进度here .

关于reactjs - 无法在 enzyme 测试中设置上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53711166/

相关文章:

reactjs - React Hook 表单属性 'type' 在类型 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>>' 中缺失,但在类型 'FieldError' 中需要

javascript - 这是一个有效的 React HoC 用例吗?

reactjs - 如何在音频叙述时根据网站上的音频实时突出显示文本

javascript - 使用 Jest 响应 js 测试 bool 属性

javascript - Jest - 添加 '</React.Fragment>' 后快照测试失败

reactjs - 单元测试 navigator.permissions.query({ name : 'geolocation' }) using Jest (React)

javascript - Jest : Unit test toHaveBeenCalled() not working

javascript - eslint 应该列在项目的依赖项中,而不是 devDependencies

reactjs - 在reactJS中的react-select中使用不同的键来搜索而不是值或标签

javascript - Jest 不加载环境变量(即使使用 --setupFiles dotenv/config)