我刚刚开始使用jest和酶。
我的单元测试工作有问题。 我使用redux-mock-store来模拟商店对象。
it('shows an li for each comment', () => {
expect(container.find('li').length).toBe(2);
});
我期待两个li元素,但我有0个li元素。
我长期陷入这个错误。
有人可以帮我弄清楚如何让这个测试通过吗?
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);
答案 0 :(得分:0)
您可以导出未装饰的CommentList组件并通过传递注释props来测试,或者您可以尝试将CommentList组件与Provider包装在一起并将商店传递给它。
<Provider store={store}>
<CommentList />
</Provider>
您可以在此处找到更多信息: http://redux.js.org/docs/recipes/WritingTests.html#connected-components
为了使您的示例正常工作,您必须将列表更改为:
const list = props.comments.map(comment => (
<li key={comment}>{comment}</li>
));
答案 1 :(得分:0)
我认为如果您使用mount
而不是shallow
内的beforeEach()
来渲染您的组件,它应该会起作用。
使用浅渲染时,渲染器不会显示您的li
组件,因为树将连接(CommentList) - &gt;评论列表 - &gt; ul - &gt;利
如果您想要保持浅浅,您还可以根据需要使用dive
更深一层。请参阅文档:
http://airbnb.io/enzyme/docs/api/ShallowWrapper/dive.html