javascript - React TestUtils 不适用于装饰器或如何使用 rewire 模拟高阶函数

标签 javascript reactjs mocha.js 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 .还是重新布线?

最佳答案

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

关于javascript - React TestUtils 不适用于装饰器或如何使用 rewire 模拟高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553167/

相关文章:

javascript - 将 html 放在 javascript 字符串中?

reactjs - RNIap.getProducts(itemSku) 返回空数组

javascript - 当生成的 HTML 看起来找到时,为什么 Enzyme 找不到我的元素?

ember.js - 如何在单元测试期间 stub 计算属性?

node.js - sinon 期望的不同参数/返回值

javascript - yepnope.js 资源回退不起作用

javascript - AngularJS ng-repeat 嵌套形式 w/socket.io

reactjs - Webpack 4 devtool 选项不适用于 webpack-dev-server

javascript - 如何使用 sinon 在另一个函数(我正在测试)中模拟一个函数?

javascript - 尝试用javascript在html中制作一个按钮