React TestUtils不适用于装饰器或如何使用重新连接来模拟高阶函数

时间:2015-07-22 03:07:15

标签: javascript reactjs mocha babeljs

我有一个更高阶的组件:

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。或重新布线?

1 个答案:

答案 0 :(得分:2)

你可以使用'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