因此,经过大量的奋斗,尝试和希望。我设法使测试正常工作,这个秘密,在我最终记得有可能之后,这很明显,就是修改 jsdom 并添加我们的
domNode ,我们只是忘了每次测试后都要卸载该组件。
Modal.test.js
import React from 'react';import { mount } from 'enzyme';import Modal from './Modal.component';import { ModalBackdrop, ModalContent, ModalDialog, ModalWrap,} from './components';describe('Modal component', () => { const Child = () => <div>Yolo</div>; let component; // add a div with #modal-root id to the global body const modalRoot = global.document.createElement('div'); modalRoot.setAttribute('id', 'modal-root'); const body = global.document.querySelector('body'); body.appendChild(modalRoot); afterEach(() => { component.unmount(); }); it('should render all the styled components and the children', () => { component = mount( <Modal> <Child /> </Modal>, ); expect(component.find(ModalBackdrop).exists()).toBeTruthy(); expect(component.find(ModalWrap).exists()).toBeTruthy(); expect(component.find(ModalWrap).contains(ModalDialog)).toBeTruthy(); expect(component.find(ModalDialog).contains(ModalContent)).toBeTruthy(); expect(component.find(ModalContent).contains(Child)).toBeTruthy(); }); it('should trigger toggle when clicked', () => { const toggle = jest.fn(); component = mount( <Modal toggle={toggle}> <Child /> </Modal>, ); component.find(ModalWrap).simulate('click'); expect(toggle.mock.calls).toHaveLength(1); expect(toggle.mock.calls[0][0]).toBeFalsy(); }); it('should mount modal on the div with id modal-root', () => { const modalRoot = global.document.querySelector('#modal-root'); expect(modalRoot.hasChildNodes()).toBeFalsy(); component = mount( <Modal> <Child /> </Modal>, ); expect(modalRoot.hasChildNodes()).toBeTruthy(); }); it('should clear the div with id modal-root on unmount', () => { const modalRoot = global.document.querySelector('#modal-root'); component = mount( <Modal> <Child /> </Modal>, ); expect(modalRoot.hasChildNodes()).toBeTruthy(); component.unmount(); expect(modalRoot.hasChildNodes()).toBeFalsy(); }); it('should set overflow hidden on the boddy element', () => { const body = global.document.querySelector('body'); expect(body.style.overflow).toBeFalsy(); component = mount( <Modal> <Child /> </Modal>, ); component.setProps({ show: true }); expect(body.style.overflow).toEqual('hidden'); component.setProps({ show: false }); expect(body.style.overflow).toBeFalsy(); });});一件大事是,酶尚未完全支持react
16,github问题。理论上所有测试都应该通过,但是它们仍然失败了,解决方案是更改模式上的包装器,而不是使用
<Fragment/>我们需要使用旧的普通格式
<div />
Modal.js 渲染方法:
render() { const ModalMarkup = ( <div> <ModalBackdrop show={this.props.show} /> <ModalWrap show={this.props.show} onClick={this.outerClick}> <ModalDialog show={this.props.show}> <ModalContent>{this.props.children}</ModalContent> </ModalDialog> </ModalWrap> </div> ); return ReactDOM.createPortal(ModalMarkup, this.el); }您可以在此处找到包含所有代码的仓库



