如何访问 React 中的方法进行单元测试

IT技术 javascript unit-testing jasmine reactjs
2021-05-07 22:48:27

我在用 React 进行单元测试时遇到了难以置信的困难。TestUtils 上的文档很少,并且没有示例。谷歌似乎只给了我几个结果。我正在使用 Jasmine,但这并不是真正让我感到悲伤的部分。

这是我尝试过的最简单的测试:

var BigButton = React.createClass({
  render: function () {
    return (
      <button className="big-submit" data-color={this.props.color} onClick={this.props.action}>{this.props.text}</button>
    );
  },
  foo: function () {},
  bar: function () {
    this.foo();
  }
});

我有一个测试

describe('BigButton', function () {
  describe('render', function () {
    it('creates a button', function () {
      var button = <BigButton />;
      TestUtils.renderIntoDocument(button);
      debugger;
    });
  });
});

我的问题是如何从外部访问 React 类中任何有意义的内容?我什至如何检查渲染是否返回按钮 HTML 元素?我知道如何使用测试间谍,但我什foo至如何找到监视的方法以及如何调用bar一切似乎都以一种完全无法测试的方式包裹起来。

2个回答

我不知道你是否知道,但 Facebook 在 Jasmine 上编写了它自己的测试库:https : //facebook.github.io/jest

他们有一个测试react的教程:https : //facebook.github.io/jest/docs/tutorial-react.html

我认为这是关于如何使用 TestUtils 的一个很好的例子,即使您不想使用 jest。要点是:

  • renderIntoDocument() 返回对分离的 DOM 节点的引用
  • 您使用像findRenderedDOMComponentWithTag()(请参阅TestUtils)之类的帮助程序从组件中获取对子节点的引用
  • 您可以getDOMNode()在您的参考中使用断言

监视方法,渲染组件之前,您可以通过访问方法对象 var methods = ComponentName.prototype.__reactAutoBindMap

然后(用茉莉花)你可以说: var methodSpy = spyOn(methods, 'methodName').and.callThrough()

然后你可以渲染组件: widget = TestUtils.renderIntoDocument(React.createElement(ComponentName, params))