Reputation: 313
I am unit testing react component. One component imports other component and use its props. Here are jsx files :
class First extends React.PureComponent {
render() {
const { name, isSelected, onClick } = this.props;
const activeClass = isSelected ? styles.active : '';
return (
<div
className={`${styles.first} ${activeClass}`}
role="button"
tabIndex={0}
onClick={() => onClick(name)}
>
{name}
</div>
);
}
}
First.propTypes = {
name: PropTypes.string.isRequired,
isSelected: PropTypes.bool,
onClick: PropTypes.func,
};
export default First;
Here is my second class that imports this class : i
mport First from '../First/First';
const Second = ({ values, passedVal, onClick }) => {
const second = values.map(vlaue =>
<First
key={value}
name={value}
isSelected={value === passedVal}
onClick={onClick}
/>,
);
return (
<div >
{Second}
</div>
);
};
Second.propTypes = {
values: PropTypes.arrayOf(PropTypes.string),
passedVal: PropTypes.string,
onClick: PropTypes.func,
};
export default FilterList;
Here is my test. I want to test isSelected condition in my test :
describe('Second - Unit test', () => {
let props;
let secondComponent;
const second = () => {
if (!secondComponent) {
secondComponent = shallow(<Second {...props} />);
}
return secondComponent;
};
beforeEach(() => {
props = Second.defaultProps;
secondComponent = undefined;
});
it('verify value of isSelected ', () => {
props.passedVal='value01';
props.value=['value01'];
console.log(props.isSelected);
});
It gives me undefined as this is prop of First class. How can i verify this logic here. Need to make instance of first and then check?
Upvotes: 1
Views: 914
Reputation: 73988
Wen using shallow
the test is executed on component as a unit, and does not indirectly asserting on behavior of child components. However you could check for a property of a child component using find
, example (not tested):
const wrapper = shallow(<First/>);
expect(wrapper.find(Second).first().prop('isSelected')).to.equal('yourValue');
Upvotes: 1
Reputation: 3084
props.isSelected
will be undefined, as you do not pass any value to it, and it does not have a default prop.
I think that instead of:
props.passedVal='value01';
props.value=['value01'];
You'll want to use:
secondComponent.setProps({
passedVal: 'value01',
values: ['value01']
});
Notice that in your test, the component is already mounted, and thus assigning new values to the props object will not actually affect the component. Using enzyme's setProps
will though. You can read a bit more about that: https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/setProps.md
Furthermore, isSelected
is a prop of the First
component, so please notice that when you try to check its value in the test.
Upvotes: 1