我正在尝试测试 onClick,但没有使用 Prop 调用它们:
这是 file.js 的一部分
handleSystemClick = () => {
// var message = All unsaved changes will be lost.`
confirmAlert({
title: 'Confirm Navigation',
message: ' All unsaved changes will be lost.',
childrenElement: () => <div></div>,
confirmLabel: 'Confirm',
cancelLabel: 'Cancel',
onConfirm: () => {this.setState({ toSystemEntitlments: true})},
onCancel: () => {},
})
}
handleCancelClick = () => {
window.history.back();
}
这是 file.js 的渲染方法
render()
return(
<div className='add-edit-button' id= 'test1' onClick={() => {this.handleSystemClick()}}>System</div>
<div className='add-edit-button' onClick={() => {this.handleCancelClick()}}>Cancel</div>
<div className='add-edit-button' onClick={() => {this.handleSave()}}>Save</div>
</div>
我在stackoverflow上看到了一些例子,我尝试应用以下内容:
// jest mock functions (mocks this.props.func)
// defining this.props
const baseProps = {
describe(' FunctionalEntitlement Test', () => {
let wrapper;
let tree;
beforeEach(() => wrapper = shallow(<BrowserRouter><Component {...baseProps} /></BrowserRouter>));
it("should call handlesave function on button click", () => {
// Reset info from possible previous calls of these mock functions:
baseProps.handleSave.mockClear();
wrapper.setProps({
});
wrapper.setState({ getINITIAL_STATE:""
});
wrapper.find('.add-edit-button').at(0).simulate("click");
expect(baseProps.handleSave).toHaveBeenCalled();
expect(toJson(wrapper)).toMatchSnapshot();
});
另外我如何才能基于 file.js 对前 2 次点击应用相同的方法
感谢您的帮助
最佳答案
如果您想使用 shallow
有一种方法可以获得其中一个 child 的浅包装using the dive
method .如果你必须用 BrowserRouter
包裹你的组件经常在测试中,也许值得为此提供一个辅助方法,例如:
function shallowWithBrowserRouter(component) {
return shallow(<BrowserRouter>{component}</BrowserRouter>).childAt(0).dive();
}
关于reactjs - 方法 “simulate” 旨在在 1 个节点上运行。 0 找到了。 - Jest/ enzyme ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54875265/