我使用jest,jasmine,并对test-utils做出反应进行测试。
我试图在我的组件的最外层div上获取渲染的类名 - 所以下面,因为我希望div说<div class='page-content banana'>
我想说的是:
expect(?).toEqual("page-content banana");
As show in this tutorial,我试过了 expect(rootElement.classList [0])。toEqual(&#34; page-content banana&#34;) 但即使在帖子中使用相同的代码,也会引发错误。
我甚至乐意在我的测试中运行getClassNames函数,但也无法解决这个问题。
记录我的浅输出让我:
{ type: 'div',
key: null,
ref: null,
_owner: null,
_context: {},
_store:
{ props: { className: undefined, children: [Object] },
originalProps: { className: undefined, children: [Object] } } }
//页面容器:(简化代码简化)
import React, {Component, PropTypes} from 'react';
import classnames from 'classnames';
class PageContainer extends Component {
getClassNames() {
return classnames([
'page-content',
this.props.classNames
]);
}
render() {
return (
<div className={this.getClassNames()}> // <- I want this
{this.getHeadline()}
{this.props.children}
</div>
);
}
}
export default PageContainer;
我的规格。我尝试过使用浅渲染和渲染DOM:
jest.dontMock('../../components/shared/PageContainer.jsx');
import React from 'react/addons';
import PageContainer from '../../components/shared/PageContainer.jsx';
const TestUtils = React.addons.TestUtils;
function renderedOutput(elt) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(elt);
return shallowRenderer.getRenderOutput();
}
describe('<PageContainer />', () => {
let shallowPageContainer, pageContainerRendered;
beforeEach(() => {
const component = (
<PageContainer headline='I am headline' classNames='banana'>
<p>The human torch was denied a bank loan.</p>
</PageContainer>
);
shallowPageContainer = renderedOutput(component);
pageContainerRendered = TestUtils.renderIntoDocument(component);
});
it('should have the correct class names', () => {
const renderedDOM = React.findDOMNode(pageContainerRendered);
expect(?).toEqual('page-content banana');
});
});
答案 0 :(得分:3)
这适合我,但请注意我使用普通的Jasmine和testdom而不是Jest,所以YMMV:
var rendered = TestUtils.renderIntoDocument(component);
const renderedDOM = React.findDOMNode(rendered);
expect(rendered.getAttribute("class")).toEqual("page-content banana");