Skip to content

Commit

Permalink
fix(manager-react-components): useNotifications prevent early clears
Browse files Browse the repository at this point in the history
Signed-off-by: Florian Renaut <[email protected]>
Signed-off-by: Tristan WAGNER <[email protected]>
  • Loading branch information
tristanwagner committed Nov 22, 2024
1 parent 95fddc9 commit 659448e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { vitest } from 'vitest';
import React, { useEffect } from 'react';
import { render } from '@testing-library/react';
import { render, waitFor } from '@testing-library/react';
import { useNotifications, NotificationType } from './useNotifications';
import { Notifications } from './notifications.component';

Expand Down Expand Up @@ -35,11 +35,27 @@ describe('notifications component', () => {
container = await render(<Notifications />).container;
expect(container.children.length).toBe(2);
});
it('should clear notifications', async () => {
it('should not clear notifications created within the last 1000ms', async () => {
let { container } = render(<Notifications />);
expect(container.children.length).not.toBe(0);
expect(container.children.length).toBe(2);

render(<ClearNotifications />);
container = render(<Notifications />).container;
expect(container.children.length).toBe(0);

expect(container.children.length).toBe(2);
});

it('should clear notifications older than 1000ms', async () => {
let { container } = render(<Notifications />);
expect(container.children.length).toBe(2);

await new Promise((resolve) => setTimeout(resolve, 2000));

render(<ClearNotifications />);
container = render(<Notifications />).container;

await waitFor(() => {
expect(container.children.length).toBe(0);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface Notification {
content: ReactNode;
type: NotificationType;
dismissable?: boolean;
creationTimestamp?: number;
}

export interface NotificationState {
Expand Down Expand Up @@ -44,7 +45,13 @@ export const useNotifications = create<NotificationState>((set, get) => ({
uid: state.uid + 1,
notifications: [
...state.notifications,
{ uid: state.uid, content, type, dismissable },
{
uid: state.uid,
content,
type,
dismissable,
creationTimestamp: Date.now(),
},
],
})),
addSuccess: (content: ReactNode, dismissable = false) =>
Expand All @@ -61,7 +68,12 @@ export const useNotifications = create<NotificationState>((set, get) => ({
({ uid }) => uid !== toRemoveUid,
),
})),
clearNotifications: () => set(() => ({ notifications: [] })),
clearNotifications: () =>
set((state) => ({
notifications: state.notifications.filter(
(notification) => Date.now() - notification.creationTimestamp < 1000,
),
})),
}));

export default useNotifications;

0 comments on commit 659448e

Please sign in to comment.