I'm exporting my Navbar component as so:

export const Navbar = ({ user }) => (
  <nav className={styles.navbarContainer}>
    <img src={Logo} alt={text.logoAlt} />
    <NavLink to={feedPath} className={styles.link} activeClassName={styles.activeLink}>
      {text.feedPathText}
    </NavLink>
    <NavLink to={viewingsPath} className={styles.link} activeClassName={styles.activeLink}>
      {text.viewingsPathText}
    </NavLink>
    <span className={styles.navItem}>
      <img className={styles.mapIcon} src={mapIcon} alt={text.mapAlt} />
      {text.defaultTheater}
    </span>
    <span className={styles.navItem}>
      <img className={styles.avatar} src={user.profilePictureUrl} alt={text.avatarAlt} />
      {`${user.firstName} ${user.lastName}`}
    </span>
  </nav>
);

const mapStateToProps = state => ({
  user: state.currentUser.user
});

Navbar.propTypes = {
  user: PropTypes.shape({
    profilePictureUrl: PropTypes.string,
    firstName: PropTypes.string,
    lastName: PropTypes.string
  })
};

export default connect(
  mapStateToProps,
  null
)(Navbar);

When I bring it in to test a protected route:

import React from 'react';
import { mount } from 'enzyme';
import { BrowserRouter } from 'react-router-dom';
import { ProtectedRoute } from '../index';
import { Navbar } from '../../../Navbar';

describe('Auth Component', () => {
  const user = {
    firstName: 'First',
    lastName: 'Last',
    profilePictureUrl: 'avatar.jpeg'
  };
  const props = {
    component: () => <div id="component" />,
    path: ''
  };

  const mountRoute = isAuth =>
    mount(
      <BrowserRouter>
        <Navbar user={user} />
        <ProtectedRoute isAuth={isAuth} {...props} />
      </BrowserRouter>
    );

  it('renders the component if isAuth is true', () => {
    const wrapper = mountRoute(true);
    expect(wrapper.find('#component').exists()).toBe(true);
  });
});

It gives me an error that it's expecting a store to be connected to the component.

Could not find "store" in the context of "Connect(Navbar)"

Not entirely sure why that is happening. I'm importing the plain component correctly right?

1 Answers

0
Jotakun On

Use shallow rendering instead of mount if you want to test your component without any context coming from connected components or any side effect. With mount every children component is rendered so if you have any nested component that relies on any context, that test will fail unless you mock that context in your test.

const mountRoute = isAuth =>
    shallow(
      <BrowserRouter>
        <Navbar user={user} />
        <ProtectedRoute isAuth={isAuth} {...props} />
      </BrowserRouter>
    );

Another thing you should consider is importing your default connected component instead of the class because that's the way you are using it in production, as the main Enzyme developers explained in this thread