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

时间:2018-12-10 17:59:43

标签: reactjs jestjs enzyme

我正在使用添加到上下文的方法,该方法是在final LoggerContext context = (LoggerContext) LogManager.getContext(false); final ConsoleAppender appender = context.getConfiguration().getAppender("Application"); final Filter rootFilter = appender.getFilter(); if (rootFilter instanceof CompositeFilter) { final CompositeFilter composite = (CompositeFilter)rootFilter; for (final Iterator<Filter> it = composite.iterator(); it.hasNext(); ) { final Filter filter = it.next(); // do something } } 生命周期方法中触发的。

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

我的测试:

shallow()

和我的组件:

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始终未定义。

3 个答案:

答案 0 :(得分:3)

很遗憾,enzyme还不支持createContextcontextType

您可以看到其进度here

答案 1 :(得分:3)

这很棘手,但是您可以使用对旧版API的现有支持来测试实际使用新API的组件。

根据您的情况,您可以在测试代码中执行以下操作:

import PropTypes from 'prop-types';

MyComponent.contextTypes = {
    dispatch: PropTypes.any,
};

现在shallow(<MyComponent />, { context });应该使用所需的上下文值进行浅显示。

答案 2 :(得分:0)

您可以使用模块shallow-with-context,而不是酶将支持contextType

然后您的测试如下所示:

import { shallow } from 'enzyme';
import { withContext, createContext } from 'shallow-with-context';

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

  shallow(<MyComponent />, { context });
});