I am trying to unit test one of my React components, but the Enzyme's shallow render method is saying it cannot find elements in the component. The component renders different navigation links depending on an authentication prop.
Nav component:
class Header extends Component {
renderLoginNav() {
switch(this.props.auth) {
case null:
return;
case false:
return (
<li key={ 1 }><a className="nav-link" href="/auth/google"
id="google">Login</a></li>
);
default:
return [
<li key={ 2 } className="nav-item">
<a className="nav-link" href="/lists">Dashboard</a></li>,
<li key={ 3 } className="nav-item">
<a className="nav-link" href="/credits">Credits</a></li>,
<li key={ 4 } className="nav-item">
<a className="nav-link" href="/api/logout">Logout</a></li>
];
}
}
render() {
return (
<nav>
<ul>
{this.renderLoginNav()}
</ul>
</nav>
);
}
}
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default connect(mapStateToProps)(Header);
Enzyme Test:
import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureStore from 'redux-mock-store';
import Header from './';
configure({ adapter: new Adapter() });
const middlewares = [];
const mockStore = configureStore(middlewares);
it('displays correct nav when authenticated', () => {
const initialState = { auth: {} };
const store = mockStore(initialState);
const wrapper = shallow(<Header store={store} />);
expect(wrapper.find('.nav-link').length).toBe(3);
})
When this test runs, it fails saying "expected 0 to be 3". Am I misunderstand how the shallow render method works? Or is there a flaw in how my test is setup?
Header
component and import as named import in the test caseimport {Header} from './'
; – Hardik Modhashallow
for functional unit testing on a connected component, you export the component and test it without the store. You can mock any props you'd receive from the store – vapurrmaid