大家好,我正在使用 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]);
关于javascript - 浅渲染找不到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51271646/