在 ReactJS 组件中测试方法?

Testing methods inside a ReactJS component?

我是 TDD 和我的 js 单元测试的新手,正在考虑使用 mocha/react 浅渲染器来测试我的 React 组件。我的测试组件看起来像这样:

var React = require('react');

var test = React.createClass({

    render: function() {

        return (
            <div>My custom test component ({this.props.testAttribute})</div>
        );
    },

    testFunction: function () {
        return true;
    }

});

module.exports = test;

因此,除了浅层渲染并确保组件以我需要的方式渲染(我现在可以做到),我还想测试 testFunction(),并确保它也正常运行。我该怎么做呢?

我认为这取决于你的 testFunction 是什么类型的函数。

如果与渲染密切相关,例如它是一个 onClickHandler,然后我将结合渲染对其进行测试。浅渲染在这里可能不够,你可能需要一个真正的 DOM(查看 jsDOM and/or 酶测试库)。

如果函数执行一些与渲染不紧密耦合的计算,那么您可以考虑将其提取到自己的文件中(考虑模块化和关注点分离等方面)。这样,您就可以像测试任何其他 JavaScript 代码一样单独测试它。

如果您真的想在组件内部单独测试函数,则需要一个真实的 DOM。 mocha/must 测试将如下所示:

import jsdom from "jsdom";
import TestUtils from "react/lib/ReactTestUtils";

describe("Component Test", function () {

    beforeEach(function () {
        global.document = jsdom.jsdom("<!doctype html><html><body></body></html>");
        global.window = global.document.defaultView;

        this.component = TestUtils.renderIntoDocument(<MyComponent/>);
    });

    afterEach(function () {
        delete global.document;
        delete global.window;
    });


   it("test the function", function () {
        expect(this.component.testFunction()).to.be(true);
    });
});