我刚刚开始使用jest和酶。
我有一个问题,使我的单元测试工作。我正在使用redux- mock -store来模拟store对象。
it('shows an li for each comment', () => {
expect(container.find('li').length).toBe(2);
});我期望有两个li元素,但是我得到了0个li元素。
我在这个错误中纠结了很长时间。
有没有人能帮我弄清楚怎样才能通过这项测试!?
来自jest test runner的测试结果
Error: expect(received).toBe(expected)
Expected value to be (using ===):
2
Received:
0
Expected :2
Actual :0CommentList.test.js
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);
});
});CommentList.js
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);发布于 2017-06-27 18:32:31
我认为如果您在beforeEach()中使用mount而不是shallow呈现组件,它应该是这样工作的。
使用浅层渲染时,渲染器不会深入到显示连接组件,因为树将是li ( CommentList ) -> CommentList -> ul -> li
如果需要,您还可以使用dive更深一层,以防您想要保持浅层。参见文档中的:http://airbnb.io/enzyme/docs/api/ShallowWrapper/dive.html
发布于 2017-06-27 16:02:40
您可以导出未修饰的CommentList组件并仅通过传递注释和道具进行测试,也可以尝试将CommentList组件与提供程序一起包装并将存储传递给它。
<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>
));https://stackoverflow.com/questions/44774060
复制相似问题