Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme Mount Error - TypeError: Cannot read property 'find' of undefined

There is an error

TypeError: Cannot read property 'find' of undefined

when I tested my react component. I used jest and enzyme for react app testing. I tried different methods but still got an undefined error.

test.js

import React from 'react';
import { mount } from 'enzyme';
import { StaticRouter } from 'react-router-dom';

import Button from '../index';

describe('<Button />', () => {
  let renderComponent;

  beforeEach(() => {
    renderComponent = (props = {}) => {
      mount(
        // <MemoryRouter>
        <Button href={href} {...props}>
          {children}
        </Button>,
        // </MemoryRouter>,
      );
    };
  });

  it('should render an <a> tag if no handleRoute is provided', () => {
    const renderedComponent = renderComponent();
    expect(renderedComponent.find('a')).toHaveLength(1);
  });
});

index.js (button component)

import React, { Children } from 'react';
import PropTypes from 'prop-types';

import A from './A';
// import StyledButton from './StyledButton';
import Wrapper from './Wrapper';

function Button(props) {
  // render an anchor tag => a tag
  let button = (
    <A href={props.href} onClick={props.onClick}>
      {Children.toArray(props.children)}
    </A>
  );

  return <Wrapper>{button}</Wrapper>;
}

Button.propTypes = {
  handleRoute: PropTypes.func,
  href: PropTypes.string,
  onClick: PropTypes.func,
  children: PropTypes.node.isRequired,
};

export default Button;
like image 447
Walter Chau Avatar asked Nov 12 '18 08:11

Walter Chau


1 Answers

You must return the component from your renderComponent function.

renderComponent = (props = {}) => {
  return mount(
    // <MemoryRouter>
    <Button href={href} {...props}>
      {children}
    </Button>,
    // </MemoryRouter>,
  );
};
like image 98
Tholle Avatar answered Oct 22 '22 09:10

Tholle