jas*_*unk 16 tdd unit-testing reactjs jestjs
我正在尝试使用jest-cli来测试一个反应组件是否包含其输出中的另一个组件.我无法弄清楚如何做到这一点.
这是我的组件:
DesignerPage组件
[...]
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;
Run Code Online (Sandbox Code Playgroud)
TopBar组件
/** @jsx React.DOM */
var React = require("react");
var TopBar = React.createClass({
render: function() {
return (
<nav className="top-bar">
</nav>
);
}
});
module.exports = TopBar;
Run Code Online (Sandbox Code Playgroud)
现在,我想测试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);
});
});
Run Code Online (Sandbox Code Playgroud)
但它没有通过...... :(
$ ./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
Run Code Online (Sandbox Code Playgroud)
我没有运行有问题的代码,但行:
var topbar = TestUtils.scryRenderedComponentsWithType(page, 'TopBar');
Run Code Online (Sandbox Code Playgroud)
看起来对我很怀疑.该文件似乎表明,你应该通过一个componentClass
而不是字符串.
我没有看到它如何使用字符串来识别组件类型.它可能会使用displayName
字符串来识别它,但我怀疑它会这样做.
我估计你可能想要这个:
var TopBar = require('../../src/js/pages/DesignerPage');
var topbar = TestUtils.scryRenderedComponentsWithType(page, TopBar);
Run Code Online (Sandbox Code Playgroud)
我遇到过类似的情况,我需要检查子组件是否被渲染.据我所知,除了你指定的那个模块之外,所有必需的模块都是jest.所以在你的情况下,子模型Topbar将被模拟,这导致我猜测渲染的DOM将不会如预期的那样.
至于检查子组件是否已呈现,我会这样做
expect(require('../../src/js/component/layout/TopBar.js').mock.calls.length).toBe(1)
Run Code Online (Sandbox Code Playgroud)
它基本上检查是否调用了模拟的子组件.
如果你真的想在这个级别测试TopBar组件的输出,你可能想要设置
jest.dontMock('../../src/js/component/layout/TopBar.js')
Run Code Online (Sandbox Code Playgroud)
同时告诉jest不要模拟TopBar组件,以便渲染的DOM也包括TopBar组件的输出.
我根据您在Github上的示例创建了一个repo ,用于测试子组件.有两个测试文件,一个测试用于模拟的子组件,另一个不模拟子组件.
归档时间: |
|
查看次数: |
8949 次 |
最近记录: |