Skip to content

Commit

Permalink
chore: signatures for tests (ant-design#37949)
Browse files Browse the repository at this point in the history
* fix: signatures for tests

* fix: remove unused

* fix: test cases

* fix: test cases
  • Loading branch information
zheeeng authored Oct 19, 2022
1 parent 51662df commit e91d256
Show file tree
Hide file tree
Showing 12 changed files with 66 additions and 61 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module.exports = {
'@typescript-eslint/no-unused-vars': [2, { args: 'none' }],
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 2,
'@typescript-eslint/consistent-type-imports': 2,
'@typescript-eslint/consistent-type-imports': [2, { disallowTypeAnnotations: false }],
},
},
{
Expand Down
1 change: 0 additions & 1 deletion components/_util/__tests__/easings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { easeInOutCubic } from '../easings';
describe('Test easings', () => {
it('easeInOutCubic return value', () => {
const nums: number[] = [];
// eslint-disable-next-line no-plusplus
for (let index = 0; index < 5; index++) {
nums.push(easeInOutCubic(index, 1, 5, 4));
}
Expand Down
9 changes: 3 additions & 6 deletions components/_util/__tests__/scrollTo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@ import { waitFakeTimer } from '../../../tests/utils';
import scrollTo from '../scrollTo';

describe('Test ScrollTo function', () => {
let dateNowMock: jest.SpyInstance;
const dateNowMock = jest.spyOn(Date, 'now');

beforeAll(() => {
jest.useFakeTimers();
});

beforeEach(() => {
dateNowMock = jest
.spyOn(Date, 'now')
.mockImplementationOnce(() => 0)
.mockImplementationOnce(() => 1000);
dateNowMock.mockReturnValueOnce(0).mockReturnValueOnce(1000);
});

afterAll(() => {
Expand All @@ -21,7 +18,7 @@ describe('Test ScrollTo function', () => {

afterEach(() => {
jest.clearAllTimers();
dateNowMock.mockRestore();
dateNowMock.mockClear();
});

it('test scrollTo', async () => {
Expand Down
2 changes: 1 addition & 1 deletion components/_util/__tests__/useSyncState.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { render, fireEvent } from '../../../tests/utils';

describe('Table', () => {
it('useSyncState', () => {
const Test: React.FC = () => {
const Test = () => {
const [getVal, setVal] = useSyncState('light');
return <span onClick={() => setVal('bamboo')}>{getVal()}</span>;
};
Expand Down
18 changes: 11 additions & 7 deletions components/_util/__tests__/wave.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -236,15 +236,19 @@ describe('Wave component', () => {
fakeDoc.appendChild(document.createElement('span'));
expect(fakeDoc.childNodes).toHaveLength(2);

(container.querySelector('.bamboo') as any).getRootNode = () => fakeDoc;
const elem = container.querySelector('.bamboo');

// Click should not throw
fireEvent.click(container.querySelector('.bamboo')!);
act(() => {
jest.runAllTimers();
});
if (elem) {
elem.getRootNode = () => fakeDoc;

expect(fakeDoc.querySelector('style')).toBeTruthy();
// Click should not throw
fireEvent.click(elem);
act(() => {
jest.runAllTimers();
});

expect(fakeDoc.querySelector('style')).toBeTruthy();
}

jest.useRealTimers();
});
Expand Down
7 changes: 1 addition & 6 deletions components/_util/wave.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import { composeRef, supportRef } from 'rc-util/lib/ref';
import * as React from 'react';
import { forwardRef } from 'react';
import type { ConfigConsumerProps, CSPConfig } from '../config-provider';
import { ConfigConsumer, ConfigContext } from '../config-provider';
import raf from './raf';
Expand Down Expand Up @@ -42,7 +41,7 @@ export interface WaveProps {
children?: React.ReactNode;
}

class InternalWave extends React.Component<WaveProps> {
class Wave extends React.Component<WaveProps> {
static contextType = ConfigContext;

private instance?: {
Expand Down Expand Up @@ -237,8 +236,4 @@ class InternalWave extends React.Component<WaveProps> {
}
}

const Wave = forwardRef<InternalWave, WaveProps>((props, ref) => (
<InternalWave ref={ref} {...props} />
));

export default Wave;
20 changes: 12 additions & 8 deletions components/button/__tests__/delay-timer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ const Content = () => {
};

it('Delay loading timer in Button component', () => {
const otherTimer: any = 9528;
jest.spyOn(window, 'setTimeout').mockReturnValue(otherTimer);
const otherTimer = 9528;
jest.spyOn<Window, 'setTimeout'>(window, 'setTimeout').mockReturnValue(otherTimer);
jest.restoreAllMocks();

const wrapper = render(<Content />);

const btnTimer: any = 9527;
jest.spyOn(window, 'setTimeout').mockReturnValue(btnTimer);
jest.spyOn(window, 'clearTimeout');
const setTimeoutMock = window.setTimeout as any as jest.Mock;
const clearTimeoutMock = window.clearTimeout as any as jest.Mock;
const btnTimer = 9527;
const setTimeoutMock = jest
.spyOn<Window, 'setTimeout'>(window, 'setTimeout')
.mockReturnValue(btnTimer);
const clearTimeoutMock = jest.spyOn<Window, 'clearTimeout'>(window, 'clearTimeout');

// other component may call setTimeout or clearTimeout
const setTimeoutCount = () => {
Expand All @@ -58,7 +58,11 @@ it('Delay loading timer in Button component', () => {

// trigger timer handler
act(() => {
setTimeoutMock.mock.calls[0][0]();
const timerHandler = setTimeoutMock.mock.calls[0][0];

if (typeof timerHandler === 'function') {
timerHandler();
}
});
expect(setTimeoutCount()).toBe(1);
expect(clearTimeoutCount()).toBe(0);
Expand Down
4 changes: 2 additions & 2 deletions components/button/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import { fireEvent, render, sleep } from '../../../tests/utils';
import ConfigProvider from '../../config-provider';
import type { SizeType } from '../../config-provider/SizeContext';

describe('Button', () => {
mountTest(Button);
Expand Down Expand Up @@ -38,7 +37,8 @@ describe('Button', () => {
it('warns if size is wrong', () => {
resetWarned();
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} />);
expect(mockWarn).toHaveBeenCalledWith('Warning: [antd: Button.Group] Invalid prop `size`.');

Expand Down
14 changes: 9 additions & 5 deletions components/button/__tests__/wave.test.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import React from 'react';
import Button from '..';
import { fireEvent, render, sleep } from '../../../tests/utils';
import { fireEvent, render, sleep, assertsExist } from '../../../tests/utils';

// Mock Wave ref
let waveInstanceMock: any;
let waveInstanceMock: InstanceType<typeof import('../../_util/wave').default> | null;
jest.mock('../../_util/wave', () => {
const Wave = jest.requireActual('../../_util/wave');
const Wave: typeof import('../../_util/wave') = jest.requireActual('../../_util/wave');
const WaveComponent = Wave.default;

return {
...Wave,
__esModule: true,
default: (props: any) => (
default: (props: import('../../_util/wave').WaveProps) => (
<WaveComponent
ref={(node: any) => {
ref={node => {
waveInstanceMock = node;
}}
{...props}
Expand Down Expand Up @@ -77,12 +78,14 @@ describe('click wave effect', () => {

it('should run resetEffect in transitionstart', async () => {
const wrapper = render(<Button type="primary">button</Button>);
assertsExist(waveInstanceMock);
const resetEffect = jest.spyOn(waveInstanceMock, 'resetEffect');
await clickButton(wrapper);
expect(resetEffect).toHaveBeenCalledTimes(1);
fireEvent.click(wrapper.container.querySelector('.ant-btn')!);
await sleep(10);
expect(resetEffect).toHaveBeenCalledTimes(2);
// @ts-expect-error: Property 'animationStart' is private and only accessible within class 'Wave'.ts(2341)
waveInstanceMock.animationStart = false;
fireEvent(wrapper.container.querySelector('.ant-btn')!, new Event('transitionstart'));
expect(resetEffect).toHaveBeenCalledTimes(3);
Expand All @@ -91,6 +94,7 @@ describe('click wave effect', () => {

it('should handle transitionend', async () => {
const wrapper = render(<Button type="primary">button</Button>);
assertsExist(waveInstanceMock);
const resetEffect = jest.spyOn(waveInstanceMock, 'resetEffect');
await clickButton(wrapper);
expect(resetEffect).toHaveBeenCalledTimes(1);
Expand Down
41 changes: 19 additions & 22 deletions components/calendar/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,16 @@ import Button from '../../radio/radioButton';
import Select from '../../select';
import Header, { type CalendarHeaderProps } from '../Header';

function calendarProps(): PickerPanelProps<any> {
return (global as any).calendarProps;
}

function calendarHeaderProps(): CalendarHeaderProps<any> {
return (global as any).calendarHeaderProps;
}
const ref: {
calendarProps?: PickerPanelProps<unknown>;
calendarHeaderProps?: CalendarHeaderProps<unknown>;
} = {};

jest.mock('../Header', () => {
const HeaderModule = jest.requireActual('../Header');
const HeaderComponent = HeaderModule.default;
return (props: CalendarHeaderProps<any>) => {
(global as any).calendarHeaderProps = props;
ref.calendarHeaderProps = props;
return <HeaderComponent {...props} />;
};
});
Expand All @@ -35,8 +32,8 @@ jest.mock('rc-picker', () => {
const PickerPanelComponent = RcPicker.PickerPanel;
return {
...RcPicker,
PickerPanel: (props: PickerPanelProps<any>) => {
(global as any).calendarProps = props;
PickerPanel: (props: PickerPanelProps<unknown>) => {
ref.calendarProps = props;
return <PickerPanelComponent {...props} />;
},
};
Expand Down Expand Up @@ -152,8 +149,8 @@ describe('Calendar', () => {
it('getDateRange should returns a disabledDate function', () => {
const validRange: [Moment.Moment, Moment.Moment] = [Moment('2018-02-02'), Moment('2018-05-18')];
render(<Calendar validRange={validRange} defaultValue={Moment('2018-02-02')} />);
expect(calendarProps().disabledDate?.(Moment('2018-06-02'))).toBe(true);
expect(calendarProps().disabledDate?.(Moment('2018-04-02'))).toBe(false);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-06-02'))).toBe(true);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-04-02'))).toBe(false);
});

it('validRange should work with disabledDate function', () => {
Expand All @@ -162,11 +159,11 @@ describe('Calendar', () => {
<Calendar validRange={validRange} disabledDate={data => data.isSame(Moment('2018-02-03'))} />,
);

expect(calendarProps().disabledDate?.(Moment('2018-02-01'))).toBe(true);
expect(calendarProps().disabledDate?.(Moment('2018-02-02'))).toBe(false);
expect(calendarProps().disabledDate?.(Moment('2018-02-03'))).toBe(true);
expect(calendarProps().disabledDate?.(Moment('2018-02-04'))).toBe(false);
expect(calendarProps().disabledDate?.(Moment('2018-06-01'))).toBe(true);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-01'))).toBe(true);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-02'))).toBe(false);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-03'))).toBe(true);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-02-04'))).toBe(false);
expect(ref.calendarProps?.disabledDate?.(Moment('2018-06-01'))).toBe(true);
});

it('Calendar MonthSelect should display correct label', () => {
Expand All @@ -181,19 +178,19 @@ describe('Calendar', () => {
const monthMode = 'month';
const yearMode = 'year';
const wrapper = render(<Calendar />);
expect(calendarHeaderProps().mode).toEqual(monthMode);
expect(ref.calendarHeaderProps?.mode).toEqual(monthMode);
wrapper.rerender(<Calendar mode={yearMode} />);
expect(calendarHeaderProps().mode).toEqual(yearMode);
expect(ref.calendarHeaderProps?.mode).toEqual(yearMode);
});

it('Calendar should switch mode', () => {
const monthMode = 'month';
const yearMode = 'year';
const onPanelChangeStub = jest.fn();
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} />);
expect(calendarHeaderProps().mode).toEqual(monthMode);
expect(ref.calendarHeaderProps?.mode).toEqual(monthMode);
expect(onPanelChangeStub).toHaveBeenCalledTimes(0);
});

Expand Down Expand Up @@ -234,7 +231,7 @@ describe('Calendar', () => {
const date = Moment(new Date(Date.UTC(2017, 7, 9, 8)));
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-month-panel').length).toBe(0);
fireEvent.click(wrapper.container.querySelector('.ant-radio-button-input[value="year"]')!);
Expand Down
4 changes: 2 additions & 2 deletions components/checkbox/__tests__/group.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -242,10 +242,10 @@ describe('CheckboxGroup', () => {
const onChange = jest.fn();

const Demo: React.FC = () => {
const [v, setV] = useState<string>('');
const [v, setV] = useState('');

React.useEffect(() => {
setTimeout(setV('1') as unknown as TimerHandler, 1000);
setV('1');
}, []);

return (
Expand Down
5 changes: 5 additions & 0 deletions tests/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 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') {
MockDate.set(dateString);
}
Expand Down

0 comments on commit e91d256

Please sign in to comment.