Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import React from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { HighlightCardOptions } from './HighlightCardOptions';

const mockSubscribe = jest.fn().mockResolvedValue(undefined);
const mockUnsubscribe = jest.fn().mockResolvedValue(undefined);
const mockDisplayToast = jest.fn();
const mockUseAuth = jest.fn();
const mockUseConditionalFeature = jest.fn();
const mockUseMajorHeadlinesSubscription = jest.fn();
const mockRouterPush = jest.fn();

jest.mock('next/router', () => ({
useRouter: () => ({ push: mockRouterPush }),
}));

jest.mock('../../../contexts/AuthContext', () => ({
useAuthContext: () => mockUseAuth(),
}));

jest.mock('../../../hooks/useConditionalFeature', () => ({
useConditionalFeature: () => mockUseConditionalFeature(),
}));

jest.mock('../../../hooks/notifications/useMajorHeadlinesSubscription', () => ({
useMajorHeadlinesSubscription: () => mockUseMajorHeadlinesSubscription(),
}));

jest.mock('../../../hooks/useToastNotification', () => ({
useToastNotification: () => ({ displayToast: mockDisplayToast }),
}));

jest.mock('../../tooltip/Tooltip', () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));

const renderComponent = () => render(<HighlightCardOptions />);

describe('HighlightCardOptions', () => {
beforeEach(() => {
jest.clearAllMocks();
mockUseAuth.mockReturnValue({ user: { id: '1' } });
mockUseConditionalFeature.mockReturnValue({ value: true });
mockUseMajorHeadlinesSubscription.mockReturnValue({
isSubscribed: false,
isLoading: false,
subscribe: mockSubscribe,
unsubscribe: mockUnsubscribe,
});
});

it('should render bell button when feature is on and user is logged in', () => {
renderComponent();

expect(
screen.getByRole('button', { name: 'Get real-time alerts' }),
).toBeInTheDocument();
});

it('should not render for guests', () => {
mockUseAuth.mockReturnValue({ user: undefined });

renderComponent();

expect(
screen.queryByRole('button', { name: 'Get real-time alerts' }),
).not.toBeInTheDocument();
});

it('should not render when feature is off', () => {
mockUseConditionalFeature.mockReturnValue({ value: false });

renderComponent();

expect(
screen.queryByRole('button', { name: 'Get real-time alerts' }),
).not.toBeInTheDocument();
});

it('should subscribe and show toast with settings action when not subscribed', async () => {
renderComponent();

fireEvent.click(
screen.getByRole('button', { name: 'Get real-time alerts' }),
);

await waitFor(() => {
expect(mockSubscribe).toHaveBeenCalledWith('feed_card');
});
await waitFor(() => {
expect(mockDisplayToast).toHaveBeenCalledWith(
"You'll be the first to know when news breaks.",
expect.objectContaining({
action: expect.objectContaining({ copy: 'Settings' }),
}),
);
});
});

it('should navigate to notification settings when toast action is clicked', async () => {
renderComponent();

fireEvent.click(
screen.getByRole('button', { name: 'Get real-time alerts' }),
);

await waitFor(() => {
expect(mockDisplayToast).toHaveBeenCalled();
});

const toastArgs = mockDisplayToast.mock.calls[0][1];
toastArgs.action.onClick();

expect(mockRouterPush).toHaveBeenCalledWith('/settings/notifications');
});

it('should unsubscribe when subscribed', async () => {
mockUseMajorHeadlinesSubscription.mockReturnValue({
isSubscribed: true,
isLoading: false,
subscribe: mockSubscribe,
unsubscribe: mockUnsubscribe,
});

renderComponent();

fireEvent.click(
screen.getByRole('button', { name: 'Turn off real-time alerts' }),
);

await waitFor(() => {
expect(mockUnsubscribe).toHaveBeenCalledWith('feed_card');
});
await waitFor(() => {
expect(mockDisplayToast).toHaveBeenCalledWith(
'Real-time alerts turned off.',
);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { ReactElement } from 'react';
import React, { useState } from 'react';
import classNames from 'classnames';
import { useRouter } from 'next/router';
import { Button, ButtonSize, ButtonVariant } from '../../buttons/Button';
import { BellAddIcon, BellSubscribedIcon } from '../../icons';
import { Tooltip } from '../../tooltip/Tooltip';
import { useAuthContext } from '../../../contexts/AuthContext';
import { useMajorHeadlinesSubscription } from '../../../hooks/notifications/useMajorHeadlinesSubscription';
import { useConditionalFeature } from '../../../hooks/useConditionalFeature';
import { featureMajorHeadlinesPush } from '../../../lib/featureManagement';
import { useToastNotification } from '../../../hooks/useToastNotification';

const NOTIFICATION_SETTINGS_PATH = '/settings/notifications';

interface HighlightCardOptionsProps {
className?: string;
}

const HighlightCardOptionsContent = ({
className,
}: HighlightCardOptionsProps): ReactElement => {
const router = useRouter();
const [isPending, setIsPending] = useState(false);
const { displayToast } = useToastNotification();
const { isSubscribed, isLoading, subscribe, unsubscribe } =
useMajorHeadlinesSubscription();

const handleToggle = async () => {
if (isPending || isLoading) {
return;
}
setIsPending(true);
try {
if (isSubscribed) {
await unsubscribe('feed_card');
displayToast('Real-time alerts turned off.');
return;
}
await subscribe('feed_card');
displayToast("You'll be the first to know when news breaks.", {
action: {
copy: 'Settings',
onClick: () => router.push(NOTIFICATION_SETTINGS_PATH),
},
});
} finally {
setIsPending(false);
}
};

const label = isSubscribed
? 'Turn off real-time alerts'
: 'Get real-time alerts';
const Icon = isSubscribed ? BellSubscribedIcon : BellAddIcon;

return (
<Tooltip content={label}>
<Button
type="button"
variant={ButtonVariant.Tertiary}
size={ButtonSize.Small}
icon={<Icon />}
className={classNames(
'invisible my-auto group-hover:visible',
className,
)}
aria-label={label}
onClick={handleToggle}
disabled={isPending || isLoading}
/>
</Tooltip>
);
};

export const HighlightCardOptions = ({
className,
}: HighlightCardOptionsProps): ReactElement | null => {
const auth = useAuthContext();
const user = auth?.user;
const { value: isFeatureEnabled } = useConditionalFeature({
feature: featureMajorHeadlinesPush,
shouldEvaluate: !!user,
});

if (!isFeatureEnabled || !user) {
return null;
}

return <HighlightCardOptionsContent className={className} />;
};

export default HighlightCardOptions;
2 changes: 2 additions & 0 deletions packages/shared/src/components/cards/highlight/common.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { PostHighlight } from '../../../graphql/highlights';
import { webappUrl } from '../../../lib/constants';
import { RelativeTime } from '../../utilities/RelativeTime';
import Link from '../../utilities/Link';
import { HighlightCardOptions } from './HighlightCardOptions';

export interface HighlightCardProps {
highlights: PostHighlight[];
Expand Down Expand Up @@ -117,6 +118,7 @@ export const HighlightCardContent = ({
>
Happening Now
</h3>
<HighlightCardOptions className="ml-auto" />
</header>
<div className={contentClassName}>
{highlights.map((highlight, index) => (
Expand Down
Loading
Loading