Skip to content

Commit

Permalink
test(useSetState): add case
Browse files Browse the repository at this point in the history
  • Loading branch information
coding-ice committed Jan 9, 2024
1 parent dcd1ec5 commit 3e7e7b6
Showing 1 changed file with 53 additions and 2 deletions.
55 changes: 53 additions & 2 deletions packages/hooks/src/useSetState/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { act, renderHook } from '@testing-library/react';
import useSetState from '../index';

interface IInitialState {
hello: string;
value: number;
foo?: string;
}

describe('useSetState', () => {
const setUp = <T extends object>(initialValue: T) =>
renderHook(() => {
const [state, setState] = useSetState<T>(initialValue);
const [state, setState, resetState] = useSetState<T>(initialValue);
return {
state,
setState,
resetState,
} as const;
});

Expand All @@ -18,8 +25,39 @@ describe('useSetState', () => {
expect(hook.result.current.state).toEqual({ hello: 'world' });
});

it('should support function initialValue', () => {
const hook = setUp(() => ({
hello: 'world',
}));
expect(hook.result.current.state).toEqual({ hello: 'world' });
});

it('should keep random initialValue', () => {
const random = Math.random();
const hook = setUp({
count: random,
});
act(() => {
hook.result.current.setState({ count: Math.random() });
hook.result.current.resetState();
});
expect(hook.result.current.state).toEqual({ count: random });
});

it('should keep random function initialValue', () => {
const random = Math.random();
const hook = setUp(() => ({
count: random,
}));
act(() => {
hook.result.current.setState({ count: Math.random() });
hook.result.current.resetState();
});
expect(hook.result.current.state).toEqual({ count: random });
});

it('should support object', () => {
const hook = setUp<any>({
const hook = setUp<Omit<IInitialState, 'value'>>({
hello: 'world',
});
act(() => {
Expand All @@ -37,4 +75,17 @@ describe('useSetState', () => {
});
expect(hook.result.current.state).toEqual({ count: 1 });
});

it('should support resetState', () => {
const random = Math.random();
const hook = setUp<IInitialState>({
hello: '',
value: random,
});
act(() => {
hook.result.current.setState({ hello: 'world', value: Math.random(), foo: 'bar' });
hook.result.current.resetState();
});
expect(hook.result.current.state).toEqual({ hello: '', value: random });
});
});

0 comments on commit 3e7e7b6

Please sign in to comment.