I've just started using jest and enzyme.
I'm having a problem to make my unit test work. Im using redux-mock-store to mock store object.
it('shows an li for each comment', () => {
expect(container.find('li').length).toBe(2);
});
I'm expecting two li elements but I got 0 li elements.
I've got stuck in this error for a long time.
Could anyone please help me to figure out how to make this test pass, please!?
Error: expect(received).toBe(expected)
Expected value to be (using ===):
2
Received:
0
Expected :2
Actual :0
import React, { Component } from 'react';
import { shallow, mount, render } from 'enzyme';
import configureStore from 'redux-mock-store';
import CommentList from '../../components/CommentList';
jest.unmock('../../components/CommentList');
describe('CommentList', () => {
const initialState = {comments: ['New Comment', 'Other New Comment']};
const mockStore = configureStore();
let store;
let container;
beforeEach(() => {
store = mockStore(initialState);
container = shallow(<CommentList store={store} />);
});
//This passes.
it('renders the connected component', () => {
expect(container.length).toBe(1);
});
//This fails.
it('shows an li for each comment', () => {
expect(container.find('li').length).toBe(2);
});
});
import React, { Component } from 'react';
import { connect } from 'react-redux';
const propTypes = {};
const defaultProps = {};
const CommentList = (props) => {
const list = props.comments.map((comment) => {
<li key={comment}>{comment}</li>
});
return (
<ul className="comment-list">
{list}
</ul>
)
};
function mapStateToProps(state) {
return {
comments: state.comments
}
}
CommentList.propTypes = propTypes;
CommentList.defaultProps = defaultProps;
export default connect(mapStateToProps)(CommentList);
I think it should work like that if you render your component using mount
instead of shallow
inside your beforeEach()
.
With shallow rendering the renderer is not going as deep as to show your li
components, because the tree will be connect(CommentList) -> CommentList -> ul -> li
You can also use dive
to go one level deeper if needed, in case you want to stay shallow. See in the docs:
http://airbnb.io/enzyme/docs/api/ShallowWrapper/dive.html