Browse Source

chore: signatures for tests (#37949)

* fix: signatures for tests

* fix: remove unused

* fix: test cases

* fix: test cases
pull/38102/head
Zheeeng 2 years ago
committed by GitHub
parent
commit
e91d25622b
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      .eslintrc.js
  2. 1
      components/_util/__tests__/easings.test.ts
  3. 9
      components/_util/__tests__/scrollTo.test.ts
  4. 2
      components/_util/__tests__/useSyncState.test.tsx
  5. 18
      components/_util/__tests__/wave.test.tsx
  6. 7
      components/_util/wave.tsx
  7. 20
      components/button/__tests__/delay-timer.test.tsx
  8. 4
      components/button/__tests__/index.test.tsx
  9. 14
      components/button/__tests__/wave.test.tsx
  10. 41
      components/calendar/__tests__/index.test.tsx
  11. 4
      components/checkbox/__tests__/group.test.tsx
  12. 5
      tests/utils.tsx

2
.eslintrc.js

@ -31,7 +31,7 @@ module.exports = {
'@typescript-eslint/no-unused-vars': [2, { args: 'none' }], '@typescript-eslint/no-unused-vars': [2, { args: 'none' }],
'no-unused-expressions': 'off', 'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 2, '@typescript-eslint/no-unused-expressions': 2,
'@typescript-eslint/consistent-type-imports': 2, '@typescript-eslint/consistent-type-imports': [2, { disallowTypeAnnotations: false }],
}, },
}, },
{ {

1
components/_util/__tests__/easings.test.ts

@ -3,7 +3,6 @@ import { easeInOutCubic } from '../easings';
describe('Test easings', () => { describe('Test easings', () => {
it('easeInOutCubic return value', () => { it('easeInOutCubic return value', () => {
const nums: number[] = []; const nums: number[] = [];
// eslint-disable-next-line no-plusplus
for (let index = 0; index < 5; index++) { for (let index = 0; index < 5; index++) {
nums.push(easeInOutCubic(index, 1, 5, 4)); nums.push(easeInOutCubic(index, 1, 5, 4));
} }

9
components/_util/__tests__/scrollTo.test.ts

@ -2,17 +2,14 @@ import { waitFakeTimer } from '../../../tests/utils';
import scrollTo from '../scrollTo'; import scrollTo from '../scrollTo';
describe('Test ScrollTo function', () => { describe('Test ScrollTo function', () => {
let dateNowMock: jest.SpyInstance; const dateNowMock = jest.spyOn(Date, 'now');
beforeAll(() => { beforeAll(() => {
jest.useFakeTimers(); jest.useFakeTimers();
}); });
beforeEach(() => { beforeEach(() => {
dateNowMock = jest dateNowMock.mockReturnValueOnce(0).mockReturnValueOnce(1000);
.spyOn(Date, 'now')
.mockImplementationOnce(() => 0)
.mockImplementationOnce(() => 1000);
}); });
afterAll(() => { afterAll(() => {
@ -21,7 +18,7 @@ describe('Test ScrollTo function', () => {
afterEach(() => { afterEach(() => {
jest.clearAllTimers(); jest.clearAllTimers();
dateNowMock.mockRestore(); dateNowMock.mockClear();
}); });
it('test scrollTo', async () => { it('test scrollTo', async () => {

2
components/_util/__tests__/useSyncState.test.tsx

@ -4,7 +4,7 @@ import { render, fireEvent } from '../../../tests/utils';
describe('Table', () => { describe('Table', () => {
it('useSyncState', () => { it('useSyncState', () => {
const Test: React.FC = () => { const Test = () => {
const [getVal, setVal] = useSyncState('light'); const [getVal, setVal] = useSyncState('light');
return <span onClick={() => setVal('bamboo')}>{getVal()}</span>; return <span onClick={() => setVal('bamboo')}>{getVal()}</span>;
}; };

18
components/_util/__tests__/wave.test.tsx

@ -236,15 +236,19 @@ describe('Wave component', () => {
fakeDoc.appendChild(document.createElement('span')); fakeDoc.appendChild(document.createElement('span'));
expect(fakeDoc.childNodes).toHaveLength(2); expect(fakeDoc.childNodes).toHaveLength(2);
(container.querySelector('.bamboo') as any).getRootNode = () => fakeDoc; const elem = container.querySelector('.bamboo');
// Click should not throw if (elem) {
fireEvent.click(container.querySelector('.bamboo')!); elem.getRootNode = () => fakeDoc;
act(() => {
jest.runAllTimers();
});
expect(fakeDoc.querySelector('style')).toBeTruthy(); // Click should not throw
fireEvent.click(elem);
act(() => {
jest.runAllTimers();
});
expect(fakeDoc.querySelector('style')).toBeTruthy();
}
jest.useRealTimers(); jest.useRealTimers();
}); });

7
components/_util/wave.tsx

@ -1,7 +1,6 @@
import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS'; import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import { composeRef, supportRef } from 'rc-util/lib/ref'; import { composeRef, supportRef } from 'rc-util/lib/ref';
import * as React from 'react'; import * as React from 'react';
import { forwardRef } from 'react';
import type { ConfigConsumerProps, CSPConfig } from '../config-provider'; import type { ConfigConsumerProps, CSPConfig } from '../config-provider';
import { ConfigConsumer, ConfigContext } from '../config-provider'; import { ConfigConsumer, ConfigContext } from '../config-provider';
import raf from './raf'; import raf from './raf';
@ -42,7 +41,7 @@ export interface WaveProps {
children?: React.ReactNode; children?: React.ReactNode;
} }
class InternalWave extends React.Component<WaveProps> { class Wave extends React.Component<WaveProps> {
static contextType = ConfigContext; static contextType = ConfigContext;
private instance?: { private instance?: {
@ -237,8 +236,4 @@ class InternalWave extends React.Component<WaveProps> {
} }
} }
const Wave = forwardRef<InternalWave, WaveProps>((props, ref) => (
<InternalWave ref={ref} {...props} />
));
export default Wave; export default Wave;

20
components/button/__tests__/delay-timer.test.tsx

@ -29,17 +29,17 @@ const Content = () => {
}; };
it('Delay loading timer in Button component', () => { it('Delay loading timer in Button component', () => {
const otherTimer: any = 9528; const otherTimer = 9528;
jest.spyOn(window, 'setTimeout').mockReturnValue(otherTimer); jest.spyOn<Window, 'setTimeout'>(window, 'setTimeout').mockReturnValue(otherTimer);
jest.restoreAllMocks(); jest.restoreAllMocks();
const wrapper = render(<Content />); const wrapper = render(<Content />);
const btnTimer: any = 9527; const btnTimer = 9527;
jest.spyOn(window, 'setTimeout').mockReturnValue(btnTimer); const setTimeoutMock = jest
jest.spyOn(window, 'clearTimeout'); .spyOn<Window, 'setTimeout'>(window, 'setTimeout')
const setTimeoutMock = window.setTimeout as any as jest.Mock; .mockReturnValue(btnTimer);
const clearTimeoutMock = window.clearTimeout as any as jest.Mock; const clearTimeoutMock = jest.spyOn<Window, 'clearTimeout'>(window, 'clearTimeout');
// other component may call setTimeout or clearTimeout // other component may call setTimeout or clearTimeout
const setTimeoutCount = () => { const setTimeoutCount = () => {
@ -58,7 +58,11 @@ it('Delay loading timer in Button component', () => {
// trigger timer handler // trigger timer handler
act(() => { act(() => {
setTimeoutMock.mock.calls[0][0](); const timerHandler = setTimeoutMock.mock.calls[0][0];
if (typeof timerHandler === 'function') {
timerHandler();
}
}); });
expect(setTimeoutCount()).toBe(1); expect(setTimeoutCount()).toBe(1);
expect(clearTimeoutCount()).toBe(0); expect(clearTimeoutCount()).toBe(0);

4
components/button/__tests__/index.test.tsx

@ -7,7 +7,6 @@ import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest'; import rtlTest from '../../../tests/shared/rtlTest';
import { fireEvent, render, sleep } from '../../../tests/utils'; import { fireEvent, render, sleep } from '../../../tests/utils';
import ConfigProvider from '../../config-provider'; import ConfigProvider from '../../config-provider';
import type { SizeType } from '../../config-provider/SizeContext';
describe('Button', () => { describe('Button', () => {
mountTest(Button); mountTest(Button);
@ -38,7 +37,8 @@ describe('Button', () => {
it('warns if size is wrong', () => { it('warns if size is wrong', () => {
resetWarned(); resetWarned();
const mockWarn = jest.spyOn(console, 'error').mockImplementation(() => {}); const mockWarn = jest.spyOn(console, 'error').mockImplementation(() => {});
const size = 'who am I' as any as SizeType; const size = 'who am I';
// @ts-expect-error: Type '"who am I"' is not assignable to type 'SizeType'.ts(2322)
render(<Button.Group size={size} />); render(<Button.Group size={size} />);
expect(mockWarn).toHaveBeenCalledWith('Warning: [antd: Button.Group] Invalid prop `size`.'); expect(mockWarn).toHaveBeenCalledWith('Warning: [antd: Button.Group] Invalid prop `size`.');

14
components/button/__tests__/wave.test.tsx

@ -1,18 +1,19 @@
import React from 'react'; import React from 'react';
import Button from '..'; import Button from '..';
import { fireEvent, render, sleep } from '../../../tests/utils'; import { fireEvent, render, sleep, assertsExist } from '../../../tests/utils';
// Mock Wave ref // Mock Wave ref
let waveInstanceMock: any; let waveInstanceMock: InstanceType<typeof import('../../_util/wave').default> | null;
jest.mock('../../_util/wave', () => { jest.mock('../../_util/wave', () => {
const Wave = jest.requireActual('../../_util/wave'); const Wave: typeof import('../../_util/wave') = jest.requireActual('../../_util/wave');
const WaveComponent = Wave.default; const WaveComponent = Wave.default;
return { return {
...Wave, ...Wave,
__esModule: true, __esModule: true,
default: (props: any) => ( default: (props: import('../../_util/wave').WaveProps) => (
<WaveComponent <WaveComponent
ref={(node: any) => { ref={node => {
waveInstanceMock = node; waveInstanceMock = node;
}} }}
{...props} {...props}
@ -77,12 +78,14 @@ describe('click wave effect', () => {
it('should run resetEffect in transitionstart', async () => { it('should run resetEffect in transitionstart', async () => {
const wrapper = render(<Button type="primary">button</Button>); const wrapper = render(<Button type="primary">button</Button>);
assertsExist(waveInstanceMock);
const resetEffect = jest.spyOn(waveInstanceMock, 'resetEffect'); const resetEffect = jest.spyOn(waveInstanceMock, 'resetEffect');
await clickButton(wrapper); await clickButton(wrapper);
expect(resetEffect).toHaveBeenCalledTimes(1); expect(resetEffect).toHaveBeenCalledTimes(1);
fireEvent.click(wrapper.container.querySelector('.ant-btn')!); fireEvent.click(wrapper.container.querySelector('.ant-btn')!);
await sleep(10); await sleep(10);
expect(resetEffect).toHaveBeenCalledTimes(2); expect(resetEffect).toHaveBeenCalledTimes(2);
// @ts-expect-error: Property 'animationStart' is private and only accessible within class 'Wave'.ts(2341)
waveInstanceMock.animationStart = false; waveInstanceMock.animationStart = false;
fireEvent(wrapper.container.querySelector('.ant-btn')!, new Event('transitionstart')); fireEvent(wrapper.container.querySelector('.ant-btn')!, new Event('transitionstart'));
expect(resetEffect).toHaveBeenCalledTimes(3); expect(resetEffect).toHaveBeenCalledTimes(3);
@ -91,6 +94,7 @@ describe('click wave effect', () => {
it('should handle transitionend', async () => { it('should handle transitionend', async () => {
const wrapper = render(<Button type="primary">button</Button>); const wrapper = render(<Button type="primary">button</Button>);
assertsExist(waveInstanceMock);
const resetEffect = jest.spyOn(waveInstanceMock, 'resetEffect'); const resetEffect = jest.spyOn(waveInstanceMock, 'resetEffect');
await clickButton(wrapper); await clickButton(wrapper);
expect(resetEffect).toHaveBeenCalledTimes(1); expect(resetEffect).toHaveBeenCalledTimes(1);

41
components/calendar/__tests__/index.test.tsx

@ -13,19 +13,16 @@ import Button from '../../radio/radioButton';
import Select from '../../select'; import Select from '../../select';
import Header, { type CalendarHeaderProps } from '../Header'; import Header, { type CalendarHeaderProps } from '../Header';
function calendarProps(): PickerPanelProps<any> { const ref: {
return (global as any).calendarProps; calendarProps?: PickerPanelProps<unknown>;
} calendarHeaderProps?: CalendarHeaderProps<unknown>;
} = {};
function calendarHeaderProps(): CalendarHeaderProps<any> {
return (global as any).calendarHeaderProps;
}
jest.mock('../Header', () => { jest.mock('../Header', () => {
const HeaderModule = jest.requireActual('../Header'); const HeaderModule = jest.requireActual('../Header');
const HeaderComponent = HeaderModule.default; const HeaderComponent = HeaderModule.default;
return (props: CalendarHeaderProps<any>) => { return (props: CalendarHeaderProps<any>) => {
(global as any).calendarHeaderProps = props; ref.calendarHeaderProps = props;
return <HeaderComponent {...props} />; return <HeaderComponent {...props} />;
}; };
}); });
@ -35,8 +32,8 @@ jest.mock('rc-picker', () => {
const PickerPanelComponent = RcPicker.PickerPanel; const PickerPanelComponent = RcPicker.PickerPanel;
return { return {
...RcPicker, ...RcPicker,
PickerPanel: (props: PickerPanelProps<any>) => { PickerPanel: (props: PickerPanelProps<unknown>) => {
(global as any).calendarProps = props; ref.calendarProps = props;
return <PickerPanelComponent {...props} />; return <PickerPanelComponent {...props} />;
}, },
}; };
@ -152,8 +149,8 @@ describe('Calendar', () => {
it('getDateRange should returns a disabledDate function', () => { it('getDateRange should returns a disabledDate function', () => {
const validRange: [Moment.Moment, Moment.Moment] = [Moment('2018-02-02'), Moment('2018-05-18')]; const validRange: [Moment.Moment, Moment.Moment] = [Moment('2018-02-02'), Moment('2018-05-18')];
render(<Calendar validRange={validRange} defaultValue={Moment('2018-02-02')} />); render(<Calendar validRange={validRange} defaultValue={Moment('2018-02-02')} />);
expect(calendarProps().disabledDate?.(Moment('2018-06-02'))).toBe(true); expect(ref.calendarProps?.disabledDate?.(Moment('2018-06-02'))).toBe(true);
expect(calendarProps().disabledDate?.(Moment('2018-04-02'))).toBe(false); expect(ref.calendarProps?.disabledDate?.(Moment('2018-04-02'))).toBe(false);
}); });
it('validRange should work with disabledDate function', () => { it('validRange should work with disabledDate function', () => {
@ -162,11 +159,11 @@ describe('Calendar', () => {
<Calendar validRange={validRange} disabledDate={data => data.isSame(Moment('2018-02-03'))} />, <Calendar validRange={validRange} disabledDate={data => data.isSame(Moment('2018-02-03'))} />,
); );
expect(calendarProps().disabledDate?.(Moment('2018-02-01'))).toBe(true); expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-01'))).toBe(true);
expect(calendarProps().disabledDate?.(Moment('2018-02-02'))).toBe(false); expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-02'))).toBe(false);
expect(calendarProps().disabledDate?.(Moment('2018-02-03'))).toBe(true); expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-03'))).toBe(true);
expect(calendarProps().disabledDate?.(Moment('2018-02-04'))).toBe(false); expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-04'))).toBe(false);
expect(calendarProps().disabledDate?.(Moment('2018-06-01'))).toBe(true); expect(ref.calendarProps?.disabledDate?.(Moment('2018-06-01'))).toBe(true);
}); });
it('Calendar MonthSelect should display correct label', () => { it('Calendar MonthSelect should display correct label', () => {
@ -181,9 +178,9 @@ describe('Calendar', () => {
const monthMode = 'month'; const monthMode = 'month';
const yearMode = 'year'; const yearMode = 'year';
const wrapper = render(<Calendar />); const wrapper = render(<Calendar />);
expect(calendarHeaderProps().mode).toEqual(monthMode); expect(ref.calendarHeaderProps?.mode).toEqual(monthMode);
wrapper.rerender(<Calendar mode={yearMode} />); wrapper.rerender(<Calendar mode={yearMode} />);
expect(calendarHeaderProps().mode).toEqual(yearMode); expect(ref.calendarHeaderProps?.mode).toEqual(yearMode);
}); });
it('Calendar should switch mode', () => { it('Calendar should switch mode', () => {
@ -191,9 +188,9 @@ describe('Calendar', () => {
const yearMode = 'year'; const yearMode = 'year';
const onPanelChangeStub = jest.fn(); const onPanelChangeStub = jest.fn();
const wrapper = render(<Calendar mode={yearMode} onPanelChange={onPanelChangeStub} />); const wrapper = render(<Calendar mode={yearMode} onPanelChange={onPanelChangeStub} />);
expect(calendarHeaderProps().mode).toEqual(yearMode); expect(ref.calendarHeaderProps?.mode).toEqual(yearMode);
wrapper.rerender(<Calendar mode={monthMode} onPanelChange={onPanelChangeStub} />); wrapper.rerender(<Calendar mode={monthMode} onPanelChange={onPanelChangeStub} />);
expect(calendarHeaderProps().mode).toEqual(monthMode); expect(ref.calendarHeaderProps?.mode).toEqual(monthMode);
expect(onPanelChangeStub).toHaveBeenCalledTimes(0); expect(onPanelChangeStub).toHaveBeenCalledTimes(0);
}); });
@ -234,7 +231,7 @@ describe('Calendar', () => {
const date = Moment(new Date(Date.UTC(2017, 7, 9, 8))); const date = Moment(new Date(Date.UTC(2017, 7, 9, 8)));
const wrapper = render(<Calendar onPanelChange={onPanelChange} value={date} />); const wrapper = render(<Calendar onPanelChange={onPanelChange} value={date} />);
expect(calendarHeaderProps().mode).toBe('month'); expect(ref.calendarHeaderProps?.mode).toBe('month');
expect(wrapper.container.querySelectorAll('.ant-picker-date-panel').length).toBe(1); expect(wrapper.container.querySelectorAll('.ant-picker-date-panel').length).toBe(1);
expect(wrapper.container.querySelectorAll('.ant-picker-month-panel').length).toBe(0); expect(wrapper.container.querySelectorAll('.ant-picker-month-panel').length).toBe(0);
fireEvent.click(wrapper.container.querySelector('.ant-radio-button-input[value="year"]')!); fireEvent.click(wrapper.container.querySelector('.ant-radio-button-input[value="year"]')!);

4
components/checkbox/__tests__/group.test.tsx

@ -242,10 +242,10 @@ describe('CheckboxGroup', () => {
const onChange = jest.fn(); const onChange = jest.fn();
const Demo: React.FC = () => { const Demo: React.FC = () => {
const [v, setV] = useState<string>(''); const [v, setV] = useState('');
React.useEffect(() => { React.useEffect(() => {
setTimeout(setV('1') as unknown as TimerHandler, 1000); setV('1');
}, []); }, []);
return ( return (

5
tests/utils.tsx

@ -6,6 +6,11 @@ import { render, act } from '@testing-library/react';
import { _rs as onLibResize } from 'rc-resize-observer/lib/utils/observerUtil'; import { _rs as onLibResize } from 'rc-resize-observer/lib/utils/observerUtil';
import { _rs as onEsResize } from 'rc-resize-observer/es/utils/observerUtil'; import { _rs as onEsResize } from 'rc-resize-observer/es/utils/observerUtil';
export function assertsExist<T>(item: T | null | undefined): asserts item is T {
expect(item).not.toBeUndefined();
expect(item).not.toBeNull();
}
export function setMockDate(dateString = '2017-09-18T03:30:07.795') { export function setMockDate(dateString = '2017-09-18T03:30:07.795') {
MockDate.set(dateString); MockDate.set(dateString);
} }

Loading…
Cancel
Save