javascript - 测试父组件上的单击事件以显示子组件

标签 javascript reactjs jestjs enzyme

我编写了一个单元测试来测试父组件中的函数。当 func 点击时,childrend 组件渲染。但我无法让它过去。这是我的代码

const useModal = () => {
    const [isOpen, setIsShowing] = useState<boolean>(false);
    const toggle = (isOpen: boolean) => {
        setIsShowing(isOpen);
    };

    return [
        isOpen,
        toggle,
    ]
};
const Parent: React.FC = () => {
    const [isOpen, toggle] = useModal();
    return (
        <React.Fragment>
              <div
                onClick={() =>
                    toggle(true)}
                className="flex flex-col items-center justify-center h-full cursor-pointer">
                <h3 className="mb-1 text-green-500 font-bold">
                    Select coupon
                </h3>
                <i className="fas fa-ticket-alt text-4xl text-gray-400"/>
            </div>
                   ....
             <Modal title={'Coupon'}
                   isOpen={isOpen} toggle={toggle}>
            <div className="p-6 pb-8">
                <h3 className="font-medium text-gray-600 mb-4">
                    Pre-valid and valid coupons are listed
                </h3>
              ...
             </Modal>
        </React.Fragment>
    )


};

const Modal: React.FC<Props> = ({isOpen, toggle, title , children}) => {
       ....
    return (
        isOpen ? createPortal(
            <React.Fragment>
                <div className="flex absolute w-full top-0 bottom-0 justify-center items-center">
                    <div
                        className="modal-overlay absolute w-full h-full bg-black opacity-25 top-0 bottom-0"/>
                    <div ref={ref} style={{top: 100}} className="ease-in-out absolute z-50 bg-white">
                        <div className="h-12 flex flex-row justify-between border-b border-gray-300">
                            <span className="self-center ml-2 font-bold text-gray-600">{title}</span>
                            <button
                                onClick={() => toggle(false)}
                                className="focus:outline-none hover:bg-gray-300 h-10 w-10 tooltip">
                                <i className="fas fa-times text-gray-500"/>
                                <span className="tooltiptext text-xs font-thin">Close</span>
                            </button>
                        </div>
                        {children}
                    </div>
                </div>
            </React.Fragment>, el
        ) : null
    )
};

测试功能

import React from "react";
import {render, unmountComponentAtNode} from "react-dom";
import {act} from "react-dom/test-utils";
import {Provider} from 'react-redux'
import Enzyme, {mount, shallow} from 'enzyme'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk';
import Adapter from 'enzyme-adapter-react-16'

import ContentCoupon from "./index";
import {Modal} from "../components";

Enzyme.configure({adapter: new Adapter()});

const mockStore = configureMockStore([thunk]);

let container: Element | null = null;
beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement("div");
    document.body.appendChild(container);
});

afterEach(() => {
    // cleanup on exiting
    if (container) {
        unmountComponentAtNode(container);
        container.remove();
    }
    container = null;
});

const store = mockStore();
const wrapper = mount(
    <Provider store={store}>
        <ContentCoupon/>
    </Provider>
);

describe('test ContentCoupon component', () => {
    it('render correctly', () => { //pass
        expect(wrapper.find('h3').text()).toEqual("Select coupon");
        expect(wrapper.find('.font-sm')).toHaveLength(0);
    });

    it('not render modal', () => { //pass
        expect(wrapper.find('h3.font-medium text-gray-600 mb-4')).toHaveLength(0);
    });

    it('click and show modal', () => { //not pass
        wrapper.find('.cursor-pointer').simulate('click');
        expect(wrapper.find('h3.font-medium text-gray-600 mb-4')).toHaveLength(1);
    });
});

最佳答案

您应该更改此处使用的 css 选择器:

expect(wrapper.find('h3.font-medium text-gray-600 mb-4')).toHaveLength(1);

至:

expect(wrapper.find('h3.font-medium.text-gray-600.mb-4')).toHaveLength(1);
//---------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

关于javascript - 测试父组件上的单击事件以显示子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60146941/

相关文章:

javascript - 使用 Date 对象的组件在不同的时区产生不同的快照

javascript - 如果任何依赖项在路径中有 "Could not locate module",则开 Jest "src"

javascript - ExtJS 中的插件和组件之间的主要区别是什么?

javascript - 带有表单验证的 ng-show formname.inputname.$error 失败

javascript - 在渲染 react Hook 之前等待 API 数据

javascript - 可能未处理的拒绝 [1] TypeError : Cannot read property 'setState' of undefined

javascript - 在等待上下文中使用 jest 模拟导入函数

javascript - 使用谷歌地图API绘制多边形,每个多边形都必须有一个点击事件

javascript - 清除javascript中的对象内存

javascript - React Native 使用另一个函数在循环中返回多个 JSX 组件