【问题标题】:React TestUtils doesn't work with decorators or how to mock higher order functions using rewireReact TestUtils 不适用于装饰器或如何使用 rewire 模拟高阶函数
【发布时间】:2015-07-22 03:07:15
【问题描述】:

我有一个高阶组件:

import React from 'react';

function withMUI(ComposedComponent) {
  return class withMUI {
    render() {
      return <ComposedComponent {...this.props}/>;
    }
  };
}

还有一个组件:

@withMUI
class PlayerProfile extends React.Component {
  render() {
    const { name, avatar } = this.props;
    return (
      <div className="player-profile">
        <div className='profile-name'>{name}</div>
        <div>
          <Avatar src={avatar}/>
        </div>
      </div>
    );
  }
}

以及使用React.findDOMNode的(通过)测试

describe('PlayerProfile', () => {
  // profile is type of `withMUI`
  let profile = TestUtils.renderIntoDocument(<OkeyPlayerProfile/>);

  it('should work', () => {
    let elem = React.findDOMNode(profile);

    // logs successfully
    console.log(elem.querySelectorAll('.player-profile'));
  });

  // ...
});

另一个(失败的)测试使用TestUtils

   // ...
   it('should also work', () => {
     let elem = TestUtils.findComponentWithTag(profile, 'div');
     // throws can't find a match
     console.log(elem);
   });

如果我删除 @withMUI 装饰器,它会按预期工作。那么,为什么装饰器会产生TestUtils.findComponentWithTag 的效果,我该如何让它发挥作用呢?

如何模拟withMUI 函数?使用babel-plugin-rewire。还是重新布线?

【问题讨论】:

  • 当我使用findComponentWithTag 时,我记得它会返回所有匹配项,无论深度如何。如果这对你来说是一样的,我希望div 有 3 个匹配项,并且会有一个错误响应。如果您使用scryComponentsWithTag,它将返回一个包含所有匹配项的数组。数组的长度是 0 还是 3?
  • @JeffFairley 为 0,但如果我不使用 withMUI,则为 3@
  • K.谢谢。只是不得不问。

标签: javascript reactjs mocha.js babeljs


【解决方案1】:

你可以使用'babel-plugin-remove-decorators'插件

先安装插件,然后创建一个文件,内容如下,我们称之为'babelTestingHook.js'

require('babel/register')({
 'stage': 2,
 'optional': [
  'es7.classProperties',
  'es7.decorators',
  // or Whatever configs you have
  .....
],
'plugins': ['babel-plugin-remove-decorators:before']
});

像下面这样运行测试将忽略装饰器,您将能够正常测试组件

mocha ./tests/**/*.spec.js --require ./babelTestingHook.js --recursive

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2015-11-09
    • 1970-01-01
    • 2015-09-12
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多