Skip to content
300 changes: 294 additions & 6 deletions packages/shared/src/hooks/post/useViewPost.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import React from 'react';
import type { ReactNode } from 'react';
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ComponentProps, ReactNode } from 'react';
import {
act,
render,
renderHook,
screen,
waitFor,
} from '@testing-library/react';
import { QueryClient, useQuery } from '@tanstack/react-query';
import { GrowthBook } from '@growthbook/growthbook-react';
import nock from 'nock';
Expand All @@ -13,7 +19,12 @@ import { VIEW_POST_MUTATION } from '../../graphql/posts';
import { REQUEST_PROTOCOL_KEY } from '../../graphql/common';
import { generateQueryKey, RequestKey } from '../../lib/query';
import { DayOfWeek } from '../../lib/date';
import { dateFormatInTimezone } from '../../lib/timezones';
import { readStreakViewQueue } from '../../lib/streakViewQueue';
import { getStreakCelebratedKey } from '../../lib/streakDailyCelebration';
import type { ToastNotification } from '../useToastNotification';
import { TOAST_NOTIF_KEY } from '../useToastNotification';
import { LogEvent, TargetType } from '../../lib/log';
import { STREAK_REFETCH_RETRY_DELAY_MS, useViewPost } from './useViewPost';

const user = { ...loggedUser, timezone: 'Europe/Amsterdam' };
Expand Down Expand Up @@ -46,37 +57,60 @@ const renderViewPost = ({
client,
requestMethod,
flag = true,
celebrationFlag = false,
isCompanion = false,
initialStreak = streak,
alerts,
log,
settings,
}: {
client: QueryClient;
requestMethod: jest.Mock;
flag?: boolean;
celebrationFlag?: boolean;
isCompanion?: boolean;
initialStreak?: UserStreak;
alerts?: ComponentProps<typeof TestBootProvider>['alerts'];
log?: ComponentProps<typeof TestBootProvider>['log'];
settings?: ComponentProps<typeof TestBootProvider>['settings'];
}) => {
client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion });
const gb = new GrowthBook({
features: { streak_optimistic_view: { defaultValue: flag } },
features: {
streak_optimistic_view: { defaultValue: flag },
streak_daily_celebration: { defaultValue: celebrationFlag },
},
});
const getFeatureValue = jest.spyOn(gb, 'getFeatureValue');
const wrapper = ({ children }: { children: ReactNode }) => (
<TestBootProvider client={client} auth={{ user }} gb={gb}>
<TestBootProvider
client={client}
auth={{ user }}
gb={gb}
settings={{ optOutReadingStreak: false, ...settings }}
alerts={alerts}
log={log}
>
{children}
</TestBootProvider>
);

return renderHook(
const view = renderHook(
() => {
// the streak query the post page shell already has in cache
useQuery({
queryKey: streakKey,
queryFn: getReadingStreak,
initialData: streak,
initialData: initialStreak,
staleTime: Infinity,
});

return useViewPost();
},
{ wrapper },
);

return { ...view, getFeatureValue };
};

describe('useViewPost', () => {
Expand Down Expand Up @@ -310,4 +344,258 @@ describe('useViewPost', () => {
expect(client.getQueryData<UserStreak>(streakKey)).toEqual(streak);
expect(readStreakViewQueue()).toEqual([]);
});

describe('daily celebration toast', () => {
// 5 -> 6: not a milestone (the API raises the milestone modal on
// Fibonacci days), so the daily toast is the one that celebrates it
const dayFive: UserStreak = { ...streak, current: 5, max: 5 };
const daySix: UserStreak = {
...dayFive,
current: 6,
max: 6,
total: 21,
lastViewAt: new Date(),
};
const requestMethod = () =>
jest.fn().mockResolvedValue({ viewPost: { _: true } });
const getToast = () =>
client.getQueryData<ToastNotification | null>(TOAST_NOTIF_KEY);

it('should toast once on the first counted read of the day', async () => {
const logEvent = jest.fn();
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: daySix } },
});
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
celebrationFlag: true,
initialStreak: dayFive,
log: { logEvent },
});

await act(async () => {
await result.current('p1');
});

render(<>{getToast()?.message}</>);
expect(screen.getByText('Day 6! See you tomorrow.')).toBeInTheDocument();
expect(logEvent).toHaveBeenCalledTimes(1);
expect(logEvent).toHaveBeenCalledWith({
event_name: LogEvent.Impression,
target_type: TargetType.StreakDailyCelebration,
target_id: 6,
});
expect(localStorage.getItem(getStreakCelebratedKey(user.id))).toBe(
dateFormatInTimezone(new Date(), 'yyyy-MM-dd', user.timezone),
);

// a second first-view the same day (replay, second tab) stays quiet
client.setQueryData(TOAST_NOTIF_KEY, null);
client.setQueryData(streakKey, dayFive);
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: daySix } },
});

await act(async () => {
await result.current('p2');
});

await waitFor(() =>
expect(client.getQueryData<UserStreak>(streakKey)).toMatchObject({
current: 6,
}),
);
expect(getToast()).toBeNull();
expect(logEvent).toHaveBeenCalledTimes(1);
});

it('should not toast when the milestone modal is due', async () => {
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: daySix } },
});
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
celebrationFlag: true,
initialStreak: dayFive,
alerts: { alerts: { showStreakMilestone: true } },
});

await act(async () => {
await result.current('p1');
});

expect(getToast()).toBeFalsy();
expect(localStorage.getItem(getStreakCelebratedKey(user.id))).toBeNull();
});

it('should leave milestone days to the milestone modal', async () => {
// 7 -> 8 is a Fibonacci day: the API flags showStreakMilestone for it
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: serverStreak } },
});
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
celebrationFlag: true,
});

await act(async () => {
await result.current('p1');
});

expect(getToast()).toBeFalsy();
});

describe('when the refetch still has the pre-view streak', () => {
// the newView worker has not credited the read yet, so userStreak
// returns yesterday's 7 although this read makes it 8
const mockPreViewStreak = () =>
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: streak } },
});

afterEach(() => {
jest.useRealTimers();
});

it('should not toast the stale count on a milestone day', async () => {
mockPreViewStreak();
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
flag: false,
celebrationFlag: true,
});

await act(async () => {
await result.current('p1');
});

// 8 is a milestone, so the toast stays quiet instead of "Day 7!"
expect(nock.isDone()).toBe(true);
expect(getToast()).toBeFalsy();
expect(
localStorage.getItem(getStreakCelebratedKey(user.id)),
).toBeNull();
});

it('should not toast the stale count after the retry is stale too', async () => {
jest.useFakeTimers({ advanceTimers: true });
mockPreViewStreak();
mockPreViewStreak();
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
celebrationFlag: true,
});

const promise = result.current('p1');
await waitFor(() => expect(nock.pendingMocks()).toHaveLength(1));
await act(async () => {
await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS);
await promise;
});

expect(nock.isDone()).toBe(true);
expect(getToast()).toBeFalsy();
});

it('should toast the count this read lands on', async () => {
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: dayFive } },
});
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
flag: false,
celebrationFlag: true,
initialStreak: dayFive,
});

await act(async () => {
await result.current('p1');
});

render(<>{getToast()?.message}</>);
expect(
screen.getByText('Day 6! See you tomorrow.'),
).toBeInTheDocument();
});
});

it('should not evaluate the flag for users who opted out of streaks', async () => {
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: daySix } },
});
const { result, getFeatureValue } = renderViewPost({
client,
requestMethod: requestMethod(),
celebrationFlag: true,
initialStreak: dayFive,
settings: { optOutReadingStreak: true },
});

await act(async () => {
await result.current('p1');
});

expect(getToast()).toBeFalsy();
expect(
getFeatureValue.mock.calls.some(
([id]) => id === 'streak_daily_celebration',
),
).toBe(false);
});

it('should not evaluate the flag while settings are loading', async () => {
const { getFeatureValue } = renderViewPost({
client,
requestMethod: requestMethod(),
celebrationFlag: true,
settings: { loadedSettings: false },
});

await act(() => Promise.resolve());
expect(
getFeatureValue.mock.calls.some(
([id]) => id === 'streak_daily_celebration',
),
).toBe(false);
});

it('should not toast when the flag is off', async () => {
const logEvent = jest.fn();
mockGraphQL({
request: { query: USER_STREAK_QUERY },
result: { data: { userStreak: daySix } },
});
const { result } = renderViewPost({
client,
requestMethod: requestMethod(),
initialStreak: dayFive,
log: { logEvent },
});

await act(async () => {
await result.current('p1');
});

await waitFor(() =>
expect(client.getQueryData<UserStreak>(streakKey)).toMatchObject({
current: 6,
}),
);
expect(getToast()).toBeFalsy();
expect(logEvent).not.toHaveBeenCalled();
});
});
});
Loading
Loading