javascript - React js - 测试组件时如何模拟上下文

标签 javascript reactjs

我正在尝试测试一个从根组件继承上下文的组件,而不加载/渲染从根向下的所有内容。我尝试并搜索了有关如何模拟上下文的示例,但找不到任何内容(至少不使用笑话)。

这是我想要实现的目标的简化示例。

有没有一种简单的方法可以模拟reactEl.context进行测试?

/**
* Root Element that sets up & shares context
*/
class Root extends Component {
  getChildContext() {
    return { 
      language: { text: 'A String'} 
    };
  }

  render() {
    return (
      <div>
        <ElWithContext />
      </div>
    );
  }
}

Root.childContextTypes = { language: React.PropTypes.object };

/**
 * Child Element which uses context
 */
class ElWithContext extends React.Component{
  render() {
    const {language} = this.context;
    return <p>{language.text}</p>
  }
}

ElWithContext.contextTypes = { language: React.PropTypes.object }



/**
 * Example test where context is unavailable.
 */
let el = React.createElement(ElWithContext)

element = TestUtils.renderIntoDocument(el);
// ERROR: undefined is not an object (evaluating 'language.text')

describe("ElWithContext", () => {
  it('should contain textContent from context', () => {
    const node = ReactDOM.findDOMNode(element);
    expect(node.textContent).to.equal('A String');
  });
})

最佳答案

我遇到了与您相同的问题,并找到了两种方法。

第一个是您自己的方式的基本模仿:围绕我的组件创建一个包装器并用动态上下文注入(inject)它。我将源代码放在下面供感兴趣的人使用,因为它是 ES6,与您的示例不同。但这只是为了展示如何在 ES6 中完成,并且我不建议任何人使用它(我自己还没有实际测试过)

src/testUtils/mockWithContext.js

import React, { Component } from 'react';
import wrapDisplayName from 'recompose/wrapDisplayName';
import hoistStatics from 'recompose/hoistStatics';

export const defaultContext = {
  permissions: [

  ],
  user: {
    id: '1',
    display_name: 'Default user',
    email: '<your.email>+default.user@gmail.com', // Trick with "+" for infinite aliases using gmail.
    username: 'default_user',
    created: '2016-08-01T15:50:13.246Z',
  },
};

export const defaultContextType = {
  permissions: React.PropTypes.array,
  user: React.PropTypes.shape({
    id: React.PropTypes.string.isRequired,
    display_name: React.PropTypes.string.isRequired,
    email: React.PropTypes.string.isRequired,
    username: React.PropTypes.string.isRequired,
    created: React.PropTypes.string.isRequired,
  }),
};

/**
 * HOC for context
 */
const withContext = ({ context = defaultContext, contextType = defaultContextType }) => (WrappedComponent) => {
  class WithContext extends Component {
    getChildContext() {
      return context;
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }

  WithContext.displayName = wrapDisplayName(WrappedComponent, 'WithContext');
  WithContext.WrappedComponent = WrappedComponent;
  WithContext.childContextTypes = contextType;

  return WithContext;
};

export default hoistStatics(withContext);
<小时/>

正如我所说,我编写了它,但没有测试它,因为在尝试为此模拟编写测试时,我发现了一种更好的上下文注入(inject)方法

使用 Enzyme 库(它绝对是为支持 React 组件测试而构建的),能够shallow/mount/static 渲染您的组件,用于测试目的。这些方法中的每一个都允许第二个参数:上下文。

SimpleComponent.js

const SimpleComponent = React.createClass({
  contextTypes: {
    name: React.PropTypes.string,
  },
  render() {
    return <div>{this.context.name}</div>;
  },
});

SimpleComponent.test.js

const context = { name: 'foo' };
const wrapper = mount(<SimpleComponent />, { context });
expect(wrapper.text()).to.equal('foo');
wrapper.setContext({ name: 'bar' });
expect(wrapper.text()).to.equal('bar');
wrapper.setContext({ name: 'baz' });
expect(wrapper.text()).to.equal('baz');

非常简单。我还没有使用它,但它看起来像我(和你)想要做的。我想我只能把我自己的实现扔进垃圾箱了。

http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html

关于javascript - React js - 测试组件时如何模拟上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36143925/

相关文章:

JavaScript 字符串搜索

javascript - ReactJs中通过循环路由路径和组件名

javascript - 如何将数组的每个元素添加到 React 状态

reactjs - Next JS SSG如何实现无限滚动?

javascript - 使用 Cheerio 在嵌套表 td 中获取 div 文本

javascript - 针对 RegExp 的 Google Closure 编译器警告

javascript - 将 Extjs 与 HAL 集成

javascript - 在 PhoneGap 中打开新窗口/文档

javascript - React.JS,组件之间传递数据

javascript - Material UI – 全局复选框焦点样式(不是本地)