Tom
Tom

Reputation: 2661

.find('button') doesn't work with shallow

I have a functional component like this:

import React from 'react'
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core/styles';
import Icon from '@material-ui/core/Icon';

const styles = theme => ({
  button: {
    margin: theme.spacing.unit,
  },
  leftIcon: {
    marginRight: theme.spacing.unit,
  },
  rightIcon: {
    marginLeft: theme.spacing.unit,
  },
  iconSmall: {
    fontSize: 20,
  },
});

const IconLabelButtons = props => {
    const {button,rightIcon} = props.classes
    const {title,icon,click,type, variant, color} = props
    return (
        <Button variant={variant} color={color} className={button} onClick={click} type={type}>
            {title}
            {icon && <Icon className={rightIcon}>{icon}</Icon>}
        </Button>
        )
}

export default withStyles(styles)(IconLabelButtons);

So now, when I try to test it with enzyme's shallow method:

    import {shallow} from 'enzyme';
    const wrapped = shallow(<IconLabelButtons />);
    expect(wrapped.find('button').length).toEqual(1);

It says expected 1 but 0 received.

But when I do:

cosnole.log(wrapped.html()) it logs out

<button class="MuiButtonBase-root-31 MuiButton-root-5 MuiButton-text-7 MuiButton-flat-10 IconLabelButtons-button-1" tabindex="0" type="button"><span class="MuiButton-label-6">foo</span></button>

Shoulnd't shallow find it then? When I use mount it works but I thought shallow should be used for just testing one component without children components.

What am I doing wrong?

Upvotes: 0

Views: 459

Answers (1)

Will Jenkins
Will Jenkins

Reputation: 9787

You're finding an html <button>, which is a child of the Button component so won't be found in a shallow wrapper. If you call wrapped.find(Button) (capital B) instead, it will work.

Upvotes: 1

Related Questions