简体   繁体   English

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

[英]Unable to set context in an Enzyme test

I'm using a method added to the context which is triggered in the componentDidMount() lifecycle method.我正在使用添加到上下文中的方法,该方法在componentDidMount()生命周期方法中触发。

I should be able to stub the context by providing an option to Enzyme's shallow() method, but this does not get passed to my component.我应该能够通过为 Enzyme 的shallow()方法提供一个选项来存根上下文,但这不会传递到我的组件。 For example:例如:

My test:我的测试:

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

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

and my component:和我的组成部分:

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 is an object, but it has no properties - dispatch is always undefined. this.context是一个对象,但它没有属性 - dispatch总是未定义的。

Unfortunately, enzyme doesn't support createContext and contextType yet.不幸的是, enzyme还不支持createContextcontextType

You can see its progress here .你可以在这里看到它的进展。

This is quite hacky, but you can use existing support for the legacy API to test components that actually use the new API.这非常 hacky,但您可以使用对遗留 API 的现有支持来测试实际使用新 API 的组件。

In your case, you can do the following in your test code:在您的情况下,您可以在测试代码中执行以下操作:

import PropTypes from 'prop-types';

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

Now shallow(<MyComponent />, { context });现在shallow(<MyComponent />, { context }); should shallow render with your desired context value.应该浅渲染你想要的上下文值。

You can use module shallow-with-context than enzyme will support contextType .您可以使用模块shallow-with-context而不是酶将支持contextType

Then your test can look like:然后你的测试看起来像:

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 });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM