用酶和jest测试模态道具



我有一个在整个应用程序中共享的模态组件。我试着测试模态渲染与里面的一切?我得到一个错误,说没有类在模态中。不知道为什么?

这是我的代码的模式:

import FocusTrap from 'focus-trap-react';
import React from 'react';
import { FaTimes } from 'react-icons/fa';
const Modal = (props) => {
const { onClickClose, title, content, active, footer } = props;
return active ? (
<FocusTrap>
<div className="gcs_modal__background">
<div className="gcs_modal">
<div className="gcs_modal__header">
<div className="gcs_modal__icon">
<FaTimes
onClick={(e) => {
e.preventDefault();
onClickClose();
}}
/>
</div>
<h1 className="gcs_modal__title">{title}</h1>
</div>
<div className="gcs_modal__content">{content}</div>
<div className="gcs_modal__footer">{footer}</div>
</div>
</div>
</FocusTrap>
) : null;
};
export default Modal;

这是我目前为止的测试内容:

import React from 'react'
import { shallow , render} from 'enzyme';
import Modal from '../Modal'
const modal = <Modal/>
describe('Modal', () => {
it('render the modal', () => {
shallow(modal)
})
it('has a background', () => {
const wrapper = shallow(modal)
expect(wrapper.find('.gcs_modal__background')).toHaveLength(1);
// expect(wrapper.find('.gcs_modal__background').children()).toHaveLength(2);
})
})

我得到的错误是;期望(收到).toHaveLength(预计)期望长度:1接收长度:0接收对象:{}

您必须设置activeprop。否则,您的组件将不呈现任何内容(返回null,因此wrapper.find('.gcs_modal__background')将具有零长度)

这个应该可以工作:

import React from 'react'
import { shallow , render} from 'enzyme';
import Modal from '../Modal'
const modal = <Modal/>
describe('Modal', () => {
it('render the modal', () => {
shallow(modal)
})
it('has a background', () => {
const wrapper = shallow(<Modal active={true} />)
expect(wrapper.find('.gcs_modal__background')).toHaveLength(1);
// expect(wrapper.find('.gcs_modal__background').children()).toHaveLength(2);
})
})

最新更新