首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟antd钩

模拟antd钩
EN

Stack Overflow用户
提问于 2022-04-26 23:50:03
回答 1查看 348关注 0票数 1

我想测试模态组件,但是在定义cancel按钮时出现了错误,只有当它不能移动时才会呈现。

isMobile是一个变量,它是来自钩子- useBreakpoint (蚂蚁设计库钩子)的布尔值.

我不知道如何模拟这个值,也不知道如何单击该按钮。

注意:如果删除isMobile检查,则按钮单击好:)

代码语言:javascript
复制
import React from 'react'
import {Grid, Typography} from 'antd'
import {Button} from '@/components/Button'
import {Modal} from '@/components/Modal'
import translations from './translations'
import {ConfirmationModalProps} from './props'

const {Text} = Typography
const {useBreakpoint} = Grid

export const ConfirmationModal = ({visible, onClose, children}: ConfirmationModalProps) => {
    const screens = useBreakpoint()
    const isMobile = screens.xs

    return (
        <Modal
            title={translations().chargeConfirmation}
            visible={visible}
            onOk={onClose}
            onCancel={onClose}
            footer={[
                !isMobile && (
                    <Button role={'cancel-button'} type={'ghost'} key={'cancel'} onClick={onClose}>
                        { translations().cancel }
                    </Button>
                ),
                <Button type={'primary'} key={'charge'} onClick={onClose}>
                    { translations().confirm }
                </Button>
            ]}
        >
            <Text>{translations().confirmationText(children)}</Text>
        </Modal>
    )
}


describe('ConfirmationModal', () => {
    it('should should the children and close button', async () => {
        const onClose = jest.fn()

        jest.mock('antd/es/grid/hooks/useBreakpoint', () => ({
            xs: false
        }))

        render(<ConfirmationModal onClose={onClose} visible={true}>100</ConfirmationModal>)

        const child = screen.getByText('Are you sure you want to charge 100')

        expect(child).toBeTruthy()

        expect(screen.queryByTestId('cancel')).toBeDefined()

        await waitFor(() => screen.queryByTestId('cancel'))

        fireEvent.click(screen.queryByRole('cancel-button'))

        expect(onClose).toHaveBeenCalledTimes(1)
    })
})

错误是:

  1. 错误:无法触发“单击”事件--请提供DOM元素。
  2. 无法找到具有“取消按钮”角色的可访问元素。

取决于queryByRole或getByRole选择器。

怎么啦?

EN

回答 1

Stack Overflow用户

发布于 2022-09-20 07:58:01

让我们看一下useBreakpoint钩子的源代码。

代码语言:javascript
复制
import { useEffect, useRef } from 'react';
import useForceUpdate from '../../_util/hooks/useForceUpdate';
import type { ScreenMap } from '../../_util/responsiveObserve';
import ResponsiveObserve from '../../_util/responsiveObserve';

function useBreakpoint(refreshOnChange: boolean = true): ScreenMap {
  const screensRef = useRef<ScreenMap>({});
  const forceUpdate = useForceUpdate();

  useEffect(() => {
    const token = ResponsiveObserve.subscribe(supportScreens => {
      screensRef.current = supportScreens;
      if (refreshOnChange) {
        forceUpdate();
      }
    });

    return () => ResponsiveObserve.unsubscribe(token);
  }, []);

  return screensRef.current;
}

export default useBreakpoint;

它使用ResponsiveObserve.subscribe()来获取supportScreens,它调用ResponsiveObserve.register().register()方法底层使用window.matchMedia()。jestjs使用JSDOM (一个DOM实现)作为它的测试环境,但JSDOM尚未实现window.matchMedia()。所以我们需要模拟它,参见未在JSDOM中实现的模拟方法

例如。

代码语言:javascript
复制
import { render } from '@testing-library/react';
import React from 'react';
import { Grid } from 'antd';

const { useBreakpoint } = Grid;

describe('72021761', () => {
  test('should pass', () => {
    Object.defineProperty(window, 'matchMedia', {
      writable: true,
      value: jest.fn().mockImplementation(
        (query) =>
          ({
            addListener: (cb: (e: { matches: boolean }) => void) => {
              cb({ matches: query === '(max-width: 575px)' });
            },
            removeListener: jest.fn(),
            matches: query === '(max-width: 575px)',
          } as any)
      ),
    });

    let screensVar;
    function Demo() {
      const screens = useBreakpoint();
      screensVar = screens;
      return <div />;
    }
    render(<Demo />);

    expect(screensVar).toEqual({
      xs: true,
      sm: false,
      md: false,
      lg: false,
      xl: false,
      xxl: false,
    });
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72021761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档