【问题标题】:When testing a React component, is there any way to directly call its non-lifecycle methods?在测试一个 React 组件的时候,有没有办法直接调用它的非生命周期方法呢?
【发布时间】:2016-03-30 14:36:32
【问题描述】:

我正在使用 Jest,我有一些组件,例如:

var TestClass = react.createClass({
  foo: function() {
    return "test";
  },
  render: function() {
    return <div />;
  }
});

我想专门为TestClass'foo方法写一个单元测试。

我看到Call a React component method from outside 建议这应该是可能的 - 只需在测试中渲染组件并调用它:

describe("TestClass", function() { 
    it("should access internal methods", function() { 
    var test = <TestClass />

    expect(test.foo()).toBeTruthy()
  }
});

从那个问题的答案中,我希望这个测试能够通过,但是:

test.foo 不是函数

我误解了那个答案吗?

一般来说,我希望能够以这种方式测试非生命周期方法 - 它会提供更好的粒度,但如果这不可能,是否有一个明智的选择?

例如,如果没有这种能力,如何测试作为 props 传递给组件子级的方法?

【问题讨论】:

  • 我猜你的测试中的变量test 不是类的实例,而只是呈现的组件(或.renderIntoDocument 返回的任何东西)。
  • 这就是我将一个人为的堆栈溢出示例拼凑在一起的结果!将编辑
  • expect(TestClass.prototype.foo()).toBeTruthy();

标签: javascript unit-testing reactjs react-jsx jestjs


【解决方案1】:

使用renderIntoDocument:

import ReactTestUtils from 'react-addons-test-utils';

...

const test = ReactTestUtils.renderIntoDocument(
  <TestClass />
);
expect(test.foo()).toBeTruthy();

【讨论】:

  • 文档未定义...这仅适用于浏览器。 :\
  • 正确 - 毕竟我们使用的是来自 ReactTestUtils 的 renderIntoDocument :)
【解决方案2】:

如果您使用酶而不是 ReactTestUtils,并且您正在使用酶的装载渲染器,那么您可以在 ReactWrapper 上调用 .instance() 来检索 ReactComponent。

var test = mount(
  <TestClass />
);

expect(test.instance().foo()).toBeTruthy();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2019-11-27
    • 2017-02-06
    • 1970-01-01
    • 2018-05-21
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多