17

我正在尝试使用 jest-cli 来测试一个反应组件是否在其输出中包含另一个组件。我很难弄清楚如何做到这一点。

这是我的组件:

设计器页面组件

[...]
var TopBar = require('../components/layout/TopBar.js');

var DesignerPage = React.createClass({
  getInitialState: function() {
    var state = {
    };
    return state;
  },
  render: function() {
    return (
      <div> 
        <TopBar />
      </div>
    )
  }
});

module.exports = DesignerPage;

顶栏组件

/** @jsx React.DOM */
var React = require("react");

var TopBar = React.createClass({
    render: function() {
        return (
            <nav className="top-bar">
            </nav>
        );
    }
});

module.exports = TopBar;

现在,我想测试 DesignerPage 组件是否包含 TopBar 组件。这是我认为应该起作用的:

/** @jsx React.DOM */
jest.dontMock('../../src/js/pages/DesignerPage.js');
describe('DesignerPage', function() {
  it('should contain a TopBar', function() {
    var React = require('react/addons');
    var DesignerPage = require('../../src/js/pages/DesignerPage.js');
    var TestUtils = React.addons.TestUtils;

    // Render a DesignerPage into the document
    var page = TestUtils.renderIntoDocument(
      <DesignerPage />
    );

    // Verify that a TopBar is included
    var topbar = TestUtils.scryRenderedComponentsWithType(page, 'TopBar');
    expect(topbar.length).toBe(1);
  });
});

但它没有通过...... :(

$ ./node_modules/jest-cli/bin/jest.js DesignerPage
Found 1 matching test...
 FAIL  __tests__/pages/DesignerPage-test.js (4.175s)
● DesignerPage › it should contain a TopBar
  - Expected: 0 toBe: 1
        at Spec.<anonymous> (__tests__/pages/DesignerPage-test.js:16:27)
        at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
1 test failed, 0 test passed (1 total)
Run time: 6.462s
4

2 回答 2

8

我没有运行有问题的代码,但行:

var topbar = TestUtils.scryRenderedComponentsWithType(page, 'TopBar');

在我看来很可疑。文档似乎建议您应该传递 a而componentClass不是字符串。

我看不出它怎么可能使用字符串来识别组件类型。它可能会使用displayName来通过字符串来识别它,但我怀疑它会这样做。

我想你可能想要这个:

var TopBar = require('../../src/js/pages/DesignerPage');
var topbar = TestUtils.scryRenderedComponentsWithType(page, TopBar);
于 2014-10-20T20:57:47.803 回答
8

我遇到过类似的情况,我需要检查子组件是否正在渲染。据我了解,jest 会模拟所有必需的模块,但您指定不这样做的模块除外。因此,在您的情况下,子组件Topbar将被模拟,这让我猜测渲染的 DOM 不会像预期的那样。

至于检查子组件是否被渲染,我会做

expect(require('../../src/js/component/layout/TopBar.js').mock.calls.length).toBe(1)

它基本上检查是否调用了模拟的子组件。

如果您真的想在此级别测试TopBar组件的输出,您可能需要设置

jest.dontMock('../../src/js/component/layout/TopBar.js') 

以及告诉jest不要模拟TopBar组件,以便渲染的 DOM 也包含来自TopBar组件的输出。

我根据您在Github上的示例创建了一个存储库,用于测试子组件。有两个测试文件,一个测试被模拟的子组件,另一个不模拟子组件。

于 2014-10-22T04:55:54.450 回答