I followed the React documentation's advice to create a specialised component through composition:
export default class AlertPanel extends React.Component {
constructor(props) {
super(props);
}
render() {
textRows = <div>{this.props.text}</div>;
}
return (
<Alert bsStyle={this.props.style} onDismiss={this.props.onDismiss}>
{textRows}
</Alert>
);
}
... and ...
import React from 'react';
import AlertPanel from './AlertPanel';
export default class SpecialAlertPanel extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<AlertPanel text="special" />
) ;
}
}
AlertPanel
has a passing test:
it( 'should render AlertPanel to a div', function() {
const wrapper = shallow( <AlertPanel /> );
expect( wrapper.type() ).to.eql( 'div' );
});
I thought an equivalent test would work for SpecialAlertPanel
:
it( 'should render SpecialAlertPanel to a div', function() {
const wrapper = shallow( <SpecialAlertPanel /> );
expect( wrapper.type() ).to.eql( 'div' );
});
But this test fails:
expected [Function: AlertPanel] to deeply equal 'div'
Is my test or my code at fault?
Since you do shallow rendering SpecialAlertPanel is rendered down to AlertPanel but not "deeper" ( http://airbnb.io/enzyme/docs/api/ShallowWrapper/shallow.html )
Most likely you need something like
it( 'should render SpecialAlertPanel to a div', function() {
const wrapper = shallow( <SpecialAlertPanel /> );
expect(wrapper.find(AlertPanel).shallow().type()).to.eql('div');
});
From https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/type.md :
If it's a composite component, this will be the component constructor.
So SpecialAlertPanel
's wrapper type is AlertPanel
.
If you want the test to pass, wrap AlertPanel
in a div
.
Slightly different to @Igor and @RemLampa's correct answers. Another view on it is - What should you be testing SpecialAlertPanel
for?
With the examples you have shown, you have an AlertPanel
component and it is tested.
SpecialAlertPanel
's only function is to render AlertPanel
.
Testing SpecialAlertPanel
for a <div>
is duplicating AlertPanel
's test.
Really all you need to be testing is if SpecialAlertPanel
is rendering an AlertPanel
. If AlertPanel
passes it's tests and SpecialAlertPanel
passes the test to check for an AlertPanel
, then you already know that it is rendering a <div>
, without needing to explicitly test for it.
(Of course you would need to add tests to SpecialAlertPanel
if you add extra functionality in the future)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.