浅层渲染找不到组件

时间:2018-07-10 18:07:25

标签: javascript reactjs jestjs

大家好,我正在用玩笑来测试我的react应用程序。在测试组件时,我发现测试意外中断,抛出错误为

Method “props” is only meant to be run on a single node. 0 found instead.

测试文件

import React from 'react';
import {shallow} from 'enzyme';
import {AddLibraryItem} from '../../components/AddLibraryItem';
import libraryItems from '../fixtures/libraryItems';

let addLibraryItem, history, wrapper;

beforeEach(() => {
    addLibraryItem = jest.fn();
    history = {push: jest.fn()};
    wrapper = shallow(<AddLibraryItem addLibraryItem={addLibraryItem} history={history}/>);

})

test('should execute on submit button successfully', () => {
    console.log(wrapper);
    wrapper.find('LibraryItemForm').prop('onSubmit')(libraryItems[0]);
    expect(addLibraryItem).toHaveBeenLastCalledWith(libraryItems[0]);
    expect(history.push).toHaveBeenLastCalledWith("/");
});

组件

import React from 'react';
import {connect} from 'react-redux';
import LibraryItemForm from './LibraryItemForm';
import {addLibraryItem} from '../actions/libraryA';

export class AddLibraryItem extends React.Component {
    onSubmit = (libraryItem) => {
        this.props.addLibraryItem(libraryItem);
        this.props.history.push('/');
    }
    render () {
        return (
            <div>
                <LibraryItemForm onSubmit={this.onSubmit} />
            </div>
        );
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        addLibraryItem: (libraryItem) => dispatch(addLibraryItem(libraryItem))
    }
}

const ConnectedAddLibraryItem = connect(undefined, mapDispatchToProps)(AddLibraryItem);
export default ConnectedAddLibraryItem;

早期的测试工作非常好,“ LibraryItemForm”的测试工作也很好,并且渲染效果也很好。 我没有明白这是怎么回事。 有什么解决办法吗?

1 个答案:

答案 0 :(得分:1)

您可能忘记了dive()

wrapper.find(LibraryItemForm).dive().prop('onSubmit')(libraryItems[0]);

Enzyme documentation here.