-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathPostPage.tsx
More file actions
1080 lines (980 loc) · 30.7 KB
/
Copy pathPostPage.tsx
File metadata and controls
1080 lines (980 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React from 'react';
import type { RenderResult } from '@testing-library/react';
import {
act,
fireEvent,
queryByText,
render,
renderHook,
screen,
waitFor,
} from '@testing-library/react';
import type { Post, PostData } from '@dailydotdev/shared/src/graphql/posts';
import {
ADD_BOOKMARKS_MUTATION,
POST_BY_ID_QUERY,
PostType,
REMOVE_BOOKMARK_MUTATION,
UserVote,
VIEW_POST_MUTATION,
} from '@dailydotdev/shared/src/graphql/posts';
import type { PostCommentsData } from '@dailydotdev/shared/src/graphql/comments';
import { POST_COMMENTS_QUERY } from '@dailydotdev/shared/src/graphql/comments';
import type { Action } from '@dailydotdev/shared/src/graphql/actions';
import {
ActionType,
COMPLETE_ACTION_MUTATION,
COMPLETED_USER_ACTIONS,
} from '@dailydotdev/shared/src/graphql/actions';
import type { LoggedUser } from '@dailydotdev/shared/src/lib/user';
import nock from 'nock';
import { QueryClient } from '@tanstack/react-query';
import type { NextRouter } from 'next/router';
import { useRouter } from 'next/router';
import defaultUser from '@dailydotdev/shared/__tests__/fixture/loggedUser';
import type { MockedGraphQLResponse } from '@dailydotdev/shared/__tests__/helpers/graphql';
import {
completeActionMock,
mockGraphQL,
} from '@dailydotdev/shared/__tests__/helpers/graphql';
import { SourceType } from '@dailydotdev/shared/src/graphql/sources';
import { createTestSettings } from '@dailydotdev/shared/__tests__/fixture/settings';
import type { AllTagCategoriesData } from '@dailydotdev/shared/src/graphql/feedSettings';
import {
ADD_FILTERS_TO_FEED_MUTATION,
FEED_SETTINGS_QUERY,
REMOVE_FILTERS_FROM_FEED_MUTATION,
} from '@dailydotdev/shared/src/graphql/feedSettings';
import { TestBootProvider } from '@dailydotdev/shared/__tests__/helpers/boot';
import * as hooks from '@dailydotdev/shared/src/hooks/useViewSize';
import { UserVoteEntity } from '@dailydotdev/shared/src/hooks';
import { getLogContextStatic } from '@dailydotdev/shared/src/contexts/LogContext';
import { usePostPageFeed } from '@dailydotdev/shared/src/hooks/post/usePostPageFeed';
import type { Props } from '../pages/posts/[id]';
import { PostPage } from '../pages/posts/[id]';
import { getSeoDescription } from '../components/PostSEOSchema';
import { getLayout as getMainLayout } from '../components/layouts/MainLayout';
const LogContext = getLogContextStatic();
const showLogin = jest.fn();
// let nextCallback: (value: PostsEngaged) => unknown = null;
//
// jest.mock('@dailydotdev/shared/src/hooks/useSubscription', () => ({
// __esModule: true,
// default: jest
// .fn()
// .mockImplementation(
// (
// request: () => OperationOptions,
// { next }: SubscriptionCallbacks<PostsEngaged>,
// ): void => {
// nextCallback = next;
// },
// ),
// }));
// const resizeWindow = (x, y) => {
// window = Object.assign(window, { innerWidth: x, innerHeight: y });
// fireEvent(window, new Event('resize'));
// };
jest.mock('next/router', () => ({
useRouter: jest.fn(),
}));
jest.mock('@dailydotdev/shared/src/hooks/useConditionalFeature', () => ({
__esModule: true,
useConditionalFeature: (args: {
feature?: { id?: string; defaultValue?: unknown };
}) => {
if (args?.feature?.id === 'reader_modal') {
return { value: false, isLoading: false };
}
// Exercise the post-page feed with the flag enabled; its default is off.
if (args?.feature?.id === 'post_page_feed') {
return { value: true, isLoading: false };
}
return { value: args?.feature?.defaultValue, isLoading: false };
},
}));
beforeEach(() => {
nock.cleanAll();
jest.clearAllMocks();
jest.mocked(useRouter).mockImplementation(
() =>
({
isFallback: false,
pathname: '/posts',
isReady: true,
query: {},
} as unknown as NextRouter),
);
});
const defaultPost = {
id: '0e4005b2d3cf191f8c44c2718a457a1e',
title: 'Learn SQL',
type: PostType.Article,
permalink: 'http://localhost:4000/r/9CuRpr5NiEY5',
image:
'https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/22fc3ac5cc3fedf281b6e4b46e8c0ba2',
createdAt: '2019-05-16T15:16:05.000Z',
readTime: 8,
tags: ['development', 'data-science', 'sql'],
source: {
__typename: 'Source',
id: 's',
handle: 's',
permalink: 'permalink/s',
name: 'Towards Data Science',
type: SourceType.Machine,
image: 'https://media.daily.dev/image/upload/t_logo,f_auto/v1/logos/tds',
public: false,
},
upvoted: false,
downvoted: false,
commented: false,
bookmarked: false,
commentsPermalink: 'https://localhost:5002/posts/9CuRpr5NiEY5',
numUpvotes: 0,
numComments: 0,
domain: 'medium.com',
};
const createPostMock = (
data: Partial<Post> = {},
): MockedGraphQLResponse<PostData> => ({
request: {
query: POST_BY_ID_QUERY,
variables: {
id: '0e4005b2d3cf191f8c44c2718a457a1e',
},
},
result: {
data: {
post: {
...(defaultPost as Post),
...data,
},
},
},
});
const getPostFromMock = (mock: MockedGraphQLResponse<PostData>): Post => {
const result =
typeof mock.result === 'function' ? mock.result() : mock.result;
const post = result.data?.post;
if (!post) {
throw new Error('Expected post in GraphQL mock');
}
return post;
};
const getRequiredElement = <T,>(
value: T | null | undefined,
message: string,
): T => {
if (value == null) {
throw new Error(message);
}
return value;
};
const createActionsMock = (): MockedGraphQLResponse<{ actions: Action[] }> => ({
request: { query: COMPLETED_USER_ACTIONS },
result: {
data: { actions: [] },
},
});
const createCommentsMock = (): MockedGraphQLResponse<PostCommentsData> => ({
request: {
query: POST_COMMENTS_QUERY,
variables: {
postId: '0e4005b2d3cf191f8c44c2718a457a1e',
after: '',
},
},
result: {
data: {
postComments: {
pageInfo: {},
edges: [],
},
},
},
});
const mockVoteMutation = ({
vote,
onSuccess,
}: {
vote: UserVote;
onSuccess?: () => void;
}): void => {
nock('http://localhost:3000')
.post(
'/graphql',
(body: {
query?: string;
variables?: { id?: string; vote?: UserVote; entity?: UserVoteEntity };
}) =>
Boolean(
body.query?.includes('mutation Vote(') &&
body.variables?.id === defaultPost.id &&
body.variables?.vote === vote &&
body.variables?.entity === UserVoteEntity.Post,
),
)
.reply(200, () => {
onSuccess?.();
return { data: { _: true } };
});
};
const mockCompleteActionMutation = (action: ActionType): void => {
nock('http://localhost:3000')
.post(
'/graphql',
(body: { query?: string; variables?: { type?: ActionType } }) =>
Boolean(
body.query?.includes('mutation CompleteAction(') &&
body.variables?.type === action,
),
)
.reply(200, { data: { _: true } });
};
// The post page "For you" feed (PostPageFeed) fires FeedV2/AnonymousFeed with
// layout-dependent variables, so match on the operation name rather than exact
// variables. Persisted to also cover any pagination/retries.
const mockPostPageFeedQuery = (): void => {
nock('http://localhost:3000')
.persist()
.post('/graphql', (body: { query?: string }) =>
Boolean(
body.query?.includes('query FeedV2(') ||
body.query?.includes('query AnonymousFeed('),
),
)
.reply(200, {
data: { page: { pageInfo: { hasNextPage: false }, edges: [] } },
});
};
let client: QueryClient;
const logEvent = jest.fn();
function renderPost(
props: Partial<Props> = {},
mocks: MockedGraphQLResponse[] = [createPostMock(), createCommentsMock()],
user?: LoggedUser,
): RenderResult {
const resolvedUser = arguments.length < 3 ? defaultUser : user;
const defaultProps: Props = {
id: '0e4005b2d3cf191f8c44c2718a457a1e',
};
client = new QueryClient();
// Add default mock for SeenPostPollTooltip action
const defaultMocks = [
...mocks,
{
request: {
query: COMPLETE_ACTION_MUTATION,
variables: { type: ActionType.SeenPostPollTooltip },
},
result: () => ({ data: { _: true } }),
},
];
defaultMocks.forEach(mockGraphQL);
mockPostPageFeedQuery();
return render(
<TestBootProvider
client={client}
auth={{
user: resolvedUser,
shouldShowLogin: !resolvedUser,
isLoggedIn: !!resolvedUser,
showLogin,
logout: jest.fn(),
updateUser: jest.fn(),
tokenRefreshed: true,
getRedirectUri: jest.fn(),
closeLogin: jest.fn(),
isAuthReady: true,
}}
settings={createTestSettings()}
>
<LogContext.Provider
value={{
logEvent,
logEventStart: jest.fn(),
logEventEnd: jest.fn(),
sendBeacon: jest.fn(),
}}
>
{getMainLayout(<PostPage {...defaultProps} {...props} />)}
</LogContext.Provider>
</TestBootProvider>,
);
}
it('should show source name', async () => {
renderPost();
const matches = await screen.findAllByText('Towards Data Science');
expect(matches.length).toBeGreaterThan(0);
});
it('should format publication date', async () => {
renderPost();
await screen.findByText('May 16, 2019');
});
it('should format read time when available', async () => {
renderPost();
const el = await screen.findByTestId('readTime');
expect(el).toHaveTextContent('8m read time');
});
it('should hide read time when not available', async () => {
renderPost({}, [
createPostMock({ readTime: undefined }),
createCommentsMock(),
]);
await screen.findByText('May 16, 2019');
expect(screen.queryByTestId('readTime')).not.toBeInTheDocument();
});
it('should set href to the post permalink', async () => {
renderPost();
// Wait for GraphQL to return
await screen.findByText('Learn SQL');
const el = screen.getAllByTitle('Go to post')[0];
expect(el).toHaveAttribute('href', 'http://localhost:4000/r/9CuRpr5NiEY5');
});
// @TODO: fix this test
// it('should display the "read post" link on mobile resolutions', async () => {
// await resizeWindow(420, 768);
// renderPost();
// expect(await screen.findByText('Learn SQL')).toBeVisible();
// const container = await screen.findByTestId('postContainer');
// const el = await within(container).findByTestId('postActionsRead');
// expect(el).toBeInTheDocument();
// });
// @TODO: fix this test
// it('should show post title as heading', async () => {
// renderPost();
// expect(await screen.findByText('Learn SQL')).toBeVisible();
// });
it('should show post tags', async () => {
renderPost();
await screen.findByText('#development');
await screen.findByText('#data-science');
await screen.findByText('#sql');
});
it('should show post image', async () => {
renderPost();
// Wait for GraphQL to return
await screen.findByText('Learn SQL');
const el = await screen.findByAltText('Post cover image');
expect(el).toHaveAttribute(
'src',
'https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/22fc3ac5cc3fedf281b6e4b46e8c0ba2',
);
});
it('should show login on upvote click', async () => {
renderPost({}, [createPostMock(), createCommentsMock()], undefined);
const [el] = await screen.findAllByLabelText('Upvote');
fireEvent.click(el);
expect(showLogin).toBeCalledTimes(1);
});
it('should check meta tag with only summary', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
summary: 'Test summary',
}),
),
);
expect(seo).toEqual('Test summary');
});
it('should check meta tag with only description', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
description: 'Test description',
}),
),
);
expect(seo).toEqual('Test description');
});
it('should check meta tag with no description and no summary', async () => {
const seo = getSeoDescription(getPostFromMock(createPostMock({})));
expect(seo).toEqual(
'Discussion about "Learn SQL" on daily.dev - join the developer community',
);
});
it('should check meta tag with both summary and description', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
description: 'Test description',
summary: 'Test summary',
}),
),
);
expect(seo).toEqual('Test summary');
});
it('should check meta tag with empty summary and description', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
description: 'Test description',
summary: '',
}),
),
);
expect(seo).toEqual('Test description');
});
it('should check meta tag with empty summary and empty description', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
description: '',
summary: '',
}),
),
);
expect(seo).toEqual(
'Discussion about "Learn SQL" on daily.dev - join the developer community',
);
});
it('should check meta tag with no description, summary of shared post', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
title: undefined,
description: undefined,
summary: undefined,
sharedPost: {
id: 'sp1',
image: '',
permalink: 'https://daily.dev',
commentsPermalink: 'https://daily.dev',
type: PostType.Article,
title: 'GitHub is down',
},
}),
),
);
expect(seo).toEqual(
'Discussion about "GitHub is down" on daily.dev - join the developer community',
);
});
it('should check meta tag with no description, summary or title', async () => {
const seo = getSeoDescription(
getPostFromMock(
createPostMock({
title: undefined,
description: undefined,
summary: undefined,
}),
),
);
expect(seo).toEqual(
'Join the discussion on daily.dev - the developer community',
);
});
it('should send upvote mutation', async () => {
let mutationCalled = false;
mockVoteMutation({
vote: UserVote.Up,
onSuccess: () => {
mutationCalled = true;
},
});
mockCompleteActionMutation(ActionType.VotePost);
renderPost({}, [createPostMock(), createCommentsMock()]);
const [el] = await screen.findAllByLabelText('Upvote');
fireEvent.click(el);
await waitFor(() => expect(mutationCalled).toBeTruthy());
});
it('should send cancel upvote mutation', async () => {
let mutationCalled = false;
mockVoteMutation({
vote: UserVote.None,
onSuccess: () => {
mutationCalled = true;
},
});
mockCompleteActionMutation(ActionType.VotePost);
renderPost({}, [
createPostMock({
userState: {
vote: UserVote.Up,
},
}),
createCommentsMock(),
]);
const el = await screen.findByLabelText('Upvote');
fireEvent.click(el);
await waitFor(() => expect(mutationCalled).toBeTruthy());
});
it('should open new comment modal and set the correct props', async () => {
renderPost();
// Wait for GraphQL to return
await screen.findByText('Learn SQL');
const el = await screen.findByText('Comment');
fireEvent.click(el);
const [commentBox] = await screen.findAllByRole('textbox');
expect(commentBox).toBeInTheDocument();
});
it('should not show stats when they are zero', async () => {
renderPost();
const el = screen.queryByTestId('statsBar');
expect(el).not.toBeInTheDocument();
});
it('should show num upvotes when it is greater than zero', async () => {
renderPost({}, [createPostMock({ numUpvotes: 15 }), createCommentsMock()]);
const el = await screen.findByTestId('statsBar');
expect(el).toHaveTextContent('15 Upvotes');
});
it('should show num comments when it is greater than zero', async () => {
renderPost({}, [createPostMock({ numComments: 15 }), createCommentsMock()]);
const el = await screen.findByTestId('statsBar');
expect(el).toHaveTextContent('15 Comments');
});
it('should show both stats when they are greater than zero', async () => {
renderPost({}, [
createPostMock({ numUpvotes: 7, numComments: 15 }),
createCommentsMock(),
]);
const el = await screen.findByTestId('statsBar');
expect(el).toHaveTextContent('7 Upvotes15 Comments');
});
it('should show impressions when it is greater than zero', async () => {
renderPost({}, [
createPostMock({ analytics: { impressions: 15 } }),
createCommentsMock(),
]);
const el = await screen.findByTestId('statsBar');
expect(el).toHaveTextContent('15 Impressions');
});
it('should not show author link when author is null', async () => {
renderPost();
const el = screen.queryByTestId('authorLink');
expect(el).not.toBeInTheDocument();
});
it('should not show author onboarding by default', () => {
renderPost();
const el = screen.queryByTestId('authorOnboarding');
expect(el).not.toBeInTheDocument();
});
it('should show author onboarding when the query param is set', async () => {
jest.mocked(useRouter).mockImplementation(
() =>
({
isFallback: false,
query: { author: 'true' },
} as unknown as NextRouter),
);
renderPost();
const el = await screen.findByTestId('authorOnboarding');
expect(el).toBeInTheDocument();
});
/**
* TODO: Flaky test should be refactored
it('should update post on subscription message', async () => {
renderPost();
await waitFor(async () => {
const data = await client.getQueryData([
'post',
'0e4005b2d3cf191f8c44c2718a457a1e',
]);
expect(data).toBeTruthy();
});
await act(async () => {
nextCallback({
postsEngaged: {
id: '0e4005b2d3cf191f8c44c2718a457a1e',
numUpvotes: 15,
numComments: 0,
},
});
});
const el = await screen.findByTestId('statsBar');
expect(el).toHaveTextContent('15 Upvotes');
});
it('should not update post on subscription message when id is not the same', async () => {
renderPost();
await waitFor(async () => {
const data = await client.getQueryData([
'post',
'0e4005b2d3cf191f8c44c2718a457a1e',
]);
expect(data).toBeTruthy();
});
nextCallback({
postsEngaged: {
id: 'asd',
numUpvotes: 15,
numComments: 0,
},
});
const el = screen.queryByTestId('statsBar');
expect(el).not.toBeInTheDocument();
});
*/
it('should send bookmark mutation from bookmark action', async () => {
// is desktop
jest.spyOn(hooks, 'useViewSize').mockImplementation(() => true);
let mutationCalled = false;
renderPost({}, [
createPostMock(),
createCommentsMock(),
{
request: {
query: ADD_BOOKMARKS_MUTATION,
variables: { data: { postIds: ['0e4005b2d3cf191f8c44c2718a457a1e'] } },
},
result: () => {
mutationCalled = true;
return { data: { _: true } };
},
},
]);
await new Promise((resolve) => setTimeout(resolve, 100));
const [el] = await screen.findAllByLabelText('Bookmark');
fireEvent.click(el);
await waitFor(() => mutationCalled);
});
it('should send remove bookmark mutation from remove bookmark action', async () => {
// is desktop
jest.spyOn(hooks, 'useViewSize').mockImplementation(() => true);
mockGraphQL({
request: {
query: COMPLETE_ACTION_MUTATION,
variables: { type: 'bookmark_promote_mobile' },
},
result: () => {
return { data: {} };
},
});
let mutationCalled = false;
renderPost({}, [
createPostMock({ bookmarked: true }),
createCommentsMock(),
{
request: {
query: REMOVE_BOOKMARK_MUTATION,
variables: { id: '0e4005b2d3cf191f8c44c2718a457a1e' },
},
result: () => {
mutationCalled = true;
return { data: { _: true } };
},
},
completeActionMock({ action: ActionType.BookmarkPost }),
]);
await new Promise((resolve) => setTimeout(resolve, 100));
const [el] = await screen.findAllByLabelText('Remove bookmark');
fireEvent.click(el);
await waitFor(() => mutationCalled);
});
it('should not show TLDR when there is no summary', async () => {
renderPost();
const el = screen.queryByText('TLDR');
expect(el).not.toBeInTheDocument();
});
it('should show TLDR when there is a summary', async () => {
renderPost({}, [
createPostMock({ summary: 'test summary' }),
completeActionMock({ action: ActionType.BookmarkPost }),
]);
const el = await screen.findByTestId('tldr-container');
expect(el).toBeInTheDocument();
expect(el).toHaveTextContent('test summary');
// eslint-disable-next-line testing-library/no-node-access, testing-library/prefer-screen-queries
const link = queryByText(
getRequiredElement(el.parentElement, 'Expected TLDR container parent'),
'Show more',
);
expect(link).not.toBeInTheDocument();
});
it('should show full TLDR for long summaries without a Show more toggle', async () => {
const summaryText =
"Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book type specimen book type specimen book type specimen book type.Ipsum is simply dummy text of the printing and typesetting industry. book type.Ipsum is simply dummy text of the printing and typesetting industry.";
renderPost({}, [
createPostMock({ summary: summaryText }),
completeActionMock({ action: ActionType.BookmarkPost }),
]);
const el = await screen.findByTestId('tldr-container');
expect(el).toBeInTheDocument();
expect(el).toHaveTextContent(summaryText);
// eslint-disable-next-line testing-library/no-node-access, testing-library/prefer-screen-queries
const showMoreLink = queryByText(
getRequiredElement(el.parentElement, 'Expected TLDR container parent'),
'Show more',
);
expect(showMoreLink).not.toBeInTheDocument();
});
it('should not show Show more link when there is a summary without reaching threshold', async () => {
renderPost({}, [
createPostMock({
summary:
'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores',
}),
]);
const el = await screen.findByTestId('tldr-container');
expect(el).toBeInTheDocument();
// eslint-disable-next-line testing-library/no-node-access, testing-library/prefer-screen-queries
const link = queryByText(
getRequiredElement(el.parentElement, 'Expected TLDR container parent'),
'Show more',
);
expect(link).not.toBeInTheDocument();
});
it('should not cut summary when there is a summary without reaching threshold', async () => {
const summaryText =
'In Node.js, errors and exceptions are different in JavaScript. There are two types of errors, programmer and operational. We use the phrase “error” to describe both, but they are quite different in reality because of their root causes. Let’s take a look at what we’ll cover to better understand how we can handle errors.';
renderPost({}, [
createPostMock({
summary: summaryText,
}),
]);
const el = await screen.findByTestId('tldr-container');
expect(el).toBeInTheDocument();
const fullSummary = await screen.findByText(summaryText);
expect(fullSummary).toBeInTheDocument();
});
it('should show login on downvote click', async () => {
renderPost({}, [createPostMock(), createCommentsMock()], undefined);
const [el] = await screen.findAllByLabelText('Downvote');
fireEvent.click(el);
expect(showLogin).toBeCalledTimes(1);
});
it('should send downvote mutation', async () => {
let mutationCalled = false;
mockVoteMutation({
vote: UserVote.Down,
onSuccess: () => {
mutationCalled = true;
},
});
mockCompleteActionMutation(ActionType.VotePost);
renderPost({}, [createPostMock(), createCommentsMock()]);
const [el] = await screen.findAllByLabelText('Downvote');
fireEvent.click(el);
await waitFor(() => expect(mutationCalled).toBeTruthy());
});
it('should send cancel downvote mutation', async () => {
let mutationCalled = false;
mockVoteMutation({
vote: UserVote.None,
onSuccess: () => {
mutationCalled = true;
},
});
mockCompleteActionMutation(ActionType.VotePost);
renderPost({}, [
createPostMock({
userState: {
vote: UserVote.Down,
},
}),
createCommentsMock(),
]);
const el = await screen.findByLabelText('Downvote');
fireEvent.click(el);
await waitFor(() => expect(mutationCalled).toBeTruthy());
});
it('should decrement number of upvotes if downvoting post that was upvoted', async () => {
let mutationCalled = false;
mockVoteMutation({
vote: UserVote.Down,
onSuccess: () => {
mutationCalled = true;
},
});
mockCompleteActionMutation(ActionType.VotePost);
renderPost({}, [
createPostMock({
userState: {
vote: UserVote.Up,
},
numUpvotes: 15,
}),
createCommentsMock(),
]);
const [downvote] = await screen.findAllByLabelText('Downvote');
fireEvent.click(downvote);
await new Promise(process.nextTick);
await waitFor(() => expect(mutationCalled).toBeTruthy());
const el = await screen.findByTestId('statsBar');
expect(el).toHaveTextContent('14 Upvotes');
});
describe('downvote flow', () => {
const createAllTagCategoriesMock = (
onSuccess?: () => void,
): MockedGraphQLResponse<AllTagCategoriesData> => ({
request: { query: FEED_SETTINGS_QUERY },
result: () => {
if (onSuccess) {
onSuccess();
}
return {
data: {
feedSettings: {
includeTags: ['react', 'golang'],
blockedTags: [],
excludeSources: [],
advancedSettings: [],
},
},
};
},
});
const prepareDownvote = async () => {
let queryCalled = false;
mockVoteMutation({ vote: UserVote.Down });
mockCompleteActionMutation(ActionType.VotePost);
renderPost({}, [
createActionsMock(),
createPostMock({
userState: {
vote: UserVote.Up,
},
numUpvotes: 15,
}),
createAllTagCategoriesMock(() => {
queryCalled = true;
}),
createCommentsMock(),
]);
const [downvote] = await screen.findAllByLabelText('Downvote');
fireEvent.click(downvote);
await new Promise(process.nextTick);
await act(async () => {
await waitFor(() => expect(queryCalled).toBeTruthy());
});
};
it('should display the tags to block panel', async () => {
await prepareDownvote();
await screen.findByText("Don't show me posts from...");
});
it('should prevent user to click block if no tags are selected', async () => {
await prepareDownvote();
const block = await screen.findByRole<HTMLButtonElement>('button', {
name: 'Block',
});
expect(block.disabled).toBe(true);
});
it('should display the option to never see the selection again if close panel', async () => {
await prepareDownvote();
let mutationCalled = false;
mockGraphQL({
request: {
query: COMPLETE_ACTION_MUTATION,
variables: { type: ActionType.HideBlockPanel },
},
result: () => {
mutationCalled = true;
return { data: { _: true } };
},
});
const close = await screen.findByTitle('Close');
fireEvent.click(close);
await screen.findAllByText('No topics were blocked');
const [dontAskAgain] = await screen.findAllByLabelText("Don't ask again");
fireEvent.click(dontAskAgain);
await waitFor(() => expect(mutationCalled).toBeTruthy());
});
it('should display the correct blocked tags count and update filters', async () => {
await prepareDownvote();
const [, tag] = await screen.findAllByTestId('blockTagButton');
fireEvent.click(tag);
let mutationCalled = false;
const label = getRequiredElement(
tag.textContent,
'Expected tag text',
).substring(1);
mockGraphQL({
request: {
query: ADD_FILTERS_TO_FEED_MUTATION,
variables: { filters: { blockedTags: [label] } },
},
result: () => {
mutationCalled = true;
return { data: { feedSettings: { id: defaultUser.id } } };
},
});
const block = await screen.findByText('Block');
fireEvent.click(block);
await waitFor(() => expect(mutationCalled).toBeTruthy());
await screen.findByText('1 topic was blocked');
let undoMutationCalled = false;
mockGraphQL({
request: {
query: REMOVE_FILTERS_FROM_FEED_MUTATION,
variables: { filters: { blockedTags: [label] } },
},
result: () => {
undoMutationCalled = true;
return { data: { _: true } };
},
});
const undo = await screen.findByText('Undo');
fireEvent.click(undo);
await waitFor(() => expect(undoMutationCalled).toBeTruthy());
});