javascript - 浅渲染找不到组件

标签 javascript reactjs jestjs

大家好,我正在使用 jest 测试我的 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”的测试也工作正常并且呈现完美。 我不明白它有什么问题。 有什么办法解决吗?

最佳答案

您可能忘记了 dive():

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

Enzyme documentation here.

关于javascript - 浅渲染找不到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51271646/

相关文章:

reactjs - 如何模拟从另一个文件导入的 jest 函数作为默认值

javascript - 生成随机颜色偏差

javascript - react-webcam(npm 包)视频大小

javascript - 如何在 React 中处理已 checkin 的输入类型 ='checkbox'?

javascript - 为什么我的考试被开 Jest 跳过了

vue.js - 无法窥探原始值;给定的未定义。 Vue JS、Jest、实用程序

javascript - Jquery更改元标记

javascript - Web 应用程序到 Android 应用程序

javascript - Angular 重置下拉值 primeng

javascript - 无法找到模块: react-accordion component