-
-
Notifications
You must be signed in to change notification settings - Fork 874
/
react-markdown.test.js
1183 lines (1046 loc) · 36.3 KB
/
react-markdown.test.js
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
const fs = require('fs')
const path = require('path')
const React = require('react')
const gfm = require('remark-gfm')
const visit = require('unist-util-visit')
const ReactDom = require('react-dom/server')
const renderer = require('react-test-renderer')
const remarkMath = require('remark-math')
const raw = require('rehype-raw')
const TeX = require('@matejmazur/react-katex')
const {render} = require('@testing-library/react')
const Markdown = require('../src/react-markdown')
const toc = require('remark-toc')
/**
* @typedef {import('unist').Position} Position
* @typedef {import('hast').Root} Root
* @typedef {import('hast').Element} Element
* @typedef {import('hast').Text} Text
* @typedef {import('react').ReactNode} ReactNode
*/
/**
* @param {ReturnType<Markdown>} input
* @returns {string}
*/
function renderHTML(input) {
return ReactDom.renderToStaticMarkup(input)
}
test('can render the most basic of documents (single paragraph)', () => {
const component = renderer.create(<Markdown>Test</Markdown>)
expect(component.toJSON()).toMatchSnapshot()
})
test('should warn when passed `source`', () => {
const warn = console.warn
console.warn = jest.fn()
// @ts-ignore runtime
expect(renderHTML(<Markdown source="a">b</Markdown>)).toEqual('<p>b</p>')
expect(console.warn).toHaveBeenCalledWith(
'[react-markdown] Warning: please use `children` instead of `source` (see <https://github.com/remarkjs/react-markdown/blob/main/changelog.md#change-source-to-children> for more info)'
)
console.warn = warn
})
test('should warn when passed `allowDangerousHtml`', () => {
const warn = console.warn
console.warn = jest.fn()
// @ts-ignore runtime
expect(renderHTML(<Markdown allowDangerousHtml>a</Markdown>)).toEqual(
'<p>a</p>'
)
expect(console.warn).toHaveBeenCalledWith(
'[react-markdown] Warning: please remove `allowDangerousHtml` (see <https://github.com/remarkjs/react-markdown/blob/main/changelog.md#remove-buggy-html-in-markdown-parser> for more info)'
)
console.warn = warn
})
test('uses passed classname for root component', () => {
const component = renderer.create(<Markdown className="md">Test</Markdown>)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle multiple paragraphs properly', () => {
const input = 'React is awesome\nAnd so is markdown\n\nCombining = epic'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle multiline paragraphs properly (softbreak, paragraphs)', () => {
const input = 'React is awesome\nAnd so is markdown \nCombining = epic'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle emphasis', () => {
const input = 'React is _totally_ *awesome*'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle bold/strong text', () => {
const input = 'React is __totally__ **awesome**'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle links without title attribute', () => {
const input = 'This is [a link](https://espen.codes/) to Espen.Codes.'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle links with title attribute', () => {
const input =
'This is [a link](https://espen.codes/ "some title") to Espen.Codes.'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle links with uppercase protocol', () => {
const input = 'This is [a link](HTTPS://ESPEN.CODES/) to Espen.Codes.'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle links with custom uri transformer', () => {
const input = 'This is [a link](https://espen.codes/) to Espen.Codes.'
/**
* @param {string} uri
* @returns {string}
*/
const transform = (uri) => uri.replace(/^https?:/, '')
const component = renderer.create(
<Markdown children={input} transformLinkUri={transform} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should use target attribute for links if specified', () => {
const input = 'This is [a link](https://espen.codes/) to Espen.Codes.'
const component = renderer.create(
<Markdown children={input} linkTarget="_blank" />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should call function to get target attribute for links if specified', () => {
const input = 'This is [a link](https://espen.codes/) to Espen.Codes.'
/**
* @param {string} uri
* @returns {string}
*/
const getTarget = (uri) => (uri.startsWith('http') ? '_blank' : undefined)
const component = renderer.create(
<Markdown children={input} linkTarget={getTarget} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should support images without alt, url, or title', () => {
const input = '![]()'
const actual = renderHTML(
<Markdown children={input} transformLinkUri={null} />
)
const expected = '<p><img src="" alt=""/></p>'
expect(actual).toEqual(expected)
})
test('should handle images without title attribute', () => {
const input = 'This is ![an image](/ninja.png).'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle images with title attribute', () => {
const input = 'This is ![an image](/ninja.png "foo bar").'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle images with custom uri transformer', () => {
const input = 'This is ![an image](/ninja.png).'
/**
* @param {string} uri
* @returns {string}
*/
const transform = (uri) => uri.replace(/\.png$/, '.jpg')
const component = renderer.create(
<Markdown children={input} transformImageUri={transform} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle image references with custom uri transformer', () => {
const input =
'This is ![The Waffle Ninja][ninja].\n\n[ninja]: https://some.host/img.png'
/**
* @param {string} uri
* @returns {string}
*/
const transform = (uri) => uri.replace(/\.png$/, '.jpg')
const component = renderer.create(
<Markdown children={input} transformImageUri={transform} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should support images references without alt, url, or title', () => {
const input = '![][a]\n\n[a]: <>'
const actual = renderHTML(
<Markdown children={input} transformLinkUri={null} />
)
const expected = '<p><img src="" alt=""/></p>'
expect(actual).toEqual(expected)
})
test('should handle images with special characters in alternative text', () => {
const input = "This is ![a ninja's image](/ninja.png)."
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should be able to render headers', () => {
expect(renderHTML(<Markdown children="# Awesome" />)).toEqual(
'<h1>Awesome</h1>'
)
expect(renderHTML(<Markdown children="## Awesome" />)).toEqual(
'<h2>Awesome</h2>'
)
expect(renderHTML(<Markdown children="### Awesome" />)).toEqual(
'<h3>Awesome</h3>'
)
expect(renderHTML(<Markdown children="#### Awesome" />)).toEqual(
'<h4>Awesome</h4>'
)
expect(renderHTML(<Markdown children="##### Awesome" />)).toEqual(
'<h5>Awesome</h5>'
)
})
test('should be able to render inline code', () => {
const input = 'Just call `renderToStaticMarkup()`, already'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle code tags without any language specification', () => {
const input = "```\nvar foo = require('bar');\nfoo();\n```"
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle code tags with language specification', () => {
const input = "```js\nvar foo = require('bar');\nfoo();\n```"
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should only use first language definition on code blocks', () => {
const input = "```js foo bar\nvar foo = require('bar');\nfoo();\n```"
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should support character references in code blocks', () => {
const input = `~~~js
ololo
i
can
haz
class
names
!@#$%^&*()_
woop
~~~`
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle code blocks by indentation', () => {
const input = [
'',
'<footer class="footer">\n',
'',
'© 2014 Foo Bar\n',
'</footer>'
].join(' ')
expect(renderHTML(<Markdown children={input} />)).toMatchSnapshot()
})
test('should handle blockquotes', () => {
const input = '> Moo\n> Tools\n> FTW\n'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle nested blockquotes', () => {
const input = [
'> > Lots of ex-Mootoolers on the React team\n>\n',
"> Totally didn't know that.\n>\n",
"> > There's a reason why it turned out so awesome\n>\n",
"> Haha I guess you're right!"
].join('')
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle tight, unordered lists', () => {
const input = '* Unordered\n* Lists\n* Are cool\n'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle loose, unordered lists', () => {
const input = '- foo\n\n- bar'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle tight, unordered lists with sublists', () => {
const input = '* Unordered\n * Lists\n * Are cool\n'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle loose, unordered lists with sublists', () => {
const input = '- foo\n\n - bar'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle ordered lists', () => {
const input = '1. Ordered\n2. Lists\n3. Are cool\n'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle ordered lists with a start index', () => {
const input = '7. Ordered\n8. Lists\n9. Are cool\n'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should pass `ordered`, `depth`, `checked`, `index` to list/listItem', () => {
const input = '- foo\n\n 2. bar\n 3. baz\n\n- root\n'
/**
* @param {Object} props
* @param {Element} props.node
* @param {boolean} props.ordered
* @param {boolean} props.checked
* @param {number} props.index
*/
const li = ({node, ordered, checked, index, ...props}) => {
expect(ordered).not.toBeUndefined()
expect(checked).toBe(null)
expect(index).toBeGreaterThanOrEqual(0)
return React.createElement('li', props)
}
/**
* @param {Object} props
* @param {Element} props.node
* @param {true} props.ordered
* @param {number} props.depth
*/
const ol = ({node, ordered, depth, ...props}) => {
expect(ordered).toBe(true)
expect(depth).toBeGreaterThanOrEqual(0)
return React.createElement('ol', props)
}
/**
* @param {Object} props
* @param {Element} props.node
* @param {false} props.ordered
* @param {number} props.depth
*/
const ul = ({node, ordered, depth, ...props}) => {
expect(ordered).toBe(false)
expect(depth).toBeGreaterThanOrEqual(0)
return React.createElement('ul', props)
}
const component = renderer.create(
<Markdown children={input} components={{li, ol, ul}} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should pass `inline: true` to inline code', () => {
const input = '```\na\n```\n\n\tb\n\n`c`'
const actual = renderHTML(
<Markdown
children={input}
components={{
/**
* @param {Object} props
* @param {Element} props.node
* @param {boolean} [props.inline]
*/
code({node, inline, ...props}) {
expect(inline === undefined || inline === true).toBe(true)
return React.createElement('code', props)
}
}}
/>
)
const expected =
'<pre><code>a\n</code></pre>\n<pre><code>b\n</code></pre>\n<p><code>c</code></p>'
expect(actual).toEqual(expected)
})
test('should pass `isHeader: boolean` to `tr`s', () => {
const input = '| a |\n| - |\n| b |\n| c |'
const actual = renderHTML(
<Markdown
children={input}
remarkPlugins={[gfm]}
components={{
/**
* @param {Object} props
* @param {Element} props.node
* @param {boolean} props.isHeader
*/
tr({node, isHeader, ...props}) {
expect(typeof isHeader === 'boolean').toBe(true)
return React.createElement('tr', props)
}
}}
/>
)
const expected =
'<table>\n<thead>\n<tr>\n<th>a</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>b</td>\n</tr>\n<tr>\n<td>c</td>\n</tr>\n</tbody>\n</table>'
expect(actual).toEqual(expected)
})
test('should pass `isHeader: true` to `th`s, `isHeader: false` to `td`s', () => {
const input = '| a |\n| - |\n| b |\n| c |'
const actual = renderHTML(
<Markdown
children={input}
remarkPlugins={[gfm]}
components={{
th({node, isHeader, ...props}) {
expect(isHeader).toBe(true)
return React.createElement('th', props)
},
td({node, isHeader, ...props}) {
expect(isHeader).toBe(false)
return React.createElement('td', props)
}
}}
/>
)
const expected =
'<table>\n<thead>\n<tr>\n<th>a</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>b</td>\n</tr>\n<tr>\n<td>c</td>\n</tr>\n</tbody>\n</table>'
expect(actual).toEqual(expected)
})
test('should pass `index: number`, `ordered: boolean`, `checked: boolean | null` to `li`s', () => {
const input = '* [x] a\n* [ ] b\n* c'
let count = 0
const actual = renderHTML(
<Markdown
children={input}
remarkPlugins={[gfm]}
components={{
li({node, checked, index, ordered, ...props}) {
expect(index).toBe(count)
expect(ordered).toBe(false)
expect(checked).toBe(count === 0 ? true : count === 1 ? false : null)
count++
return React.createElement('li', props)
}
}}
/>
)
const expected =
'<ul class="contains-task-list">\n<li class="task-list-item"><input type="checkbox" checked="" disabled=""/> a</li>\n<li class="task-list-item"><input type="checkbox" disabled=""/> b</li>\n<li>c</li>\n</ul>'
expect(actual).toEqual(expected)
})
test('should pass `level: number` to `h1`, `h2`, ...', () => {
const input = '#\n##\n###'
/**
* @param {Object} props
* @param {Element} props.node
* @param {number} props.level
*/
function heading({node, level, ...props}) {
return React.createElement(`h${level}`, props)
}
const actual = renderHTML(
<Markdown
children={input}
components={{h1: heading, h2: heading, h3: heading}}
/>
)
const expected = '<h1></h1>\n<h2></h2>\n<h3></h3>'
expect(actual).toEqual(expected)
})
test('should skip inline html with skipHtml option enabled', () => {
const input = 'I am having <strong>so</strong> much fun'
const component = renderer.create(<Markdown children={input} skipHtml />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should escape html blocks by default', () => {
const input = [
'This is a regular paragraph.\n\n<table>\n <tr>\n ',
'<td>Foo</td>\n </tr>\n</table>\n\nThis is another',
' regular paragraph.'
].join('')
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should skip html blocks if skipHtml prop is set', () => {
const input = [
'This is a regular paragraph.\n\n<table>\n <tr>\n ',
'<td>Foo</td>\n </tr>\n</table>\n\nThis is another',
' regular paragraph.'
].join('')
const component = renderer.create(<Markdown children={input} skipHtml />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should escape html blocks by default (with HTML parser plugin)', () => {
const input = [
'This is a regular paragraph.\n\n<table>\n <tr>\n ',
'<td>Foo</td>\n </tr>\n</table>\n\nThis is another',
' regular paragraph.'
].join('')
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should handle horizontal rules', () => {
const input = 'Foo\n\n------------\n\nBar'
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should set source position attributes if sourcePos option is enabled', () => {
const input = 'Foo\n\n------------\n\nBar'
const component = renderer.create(<Markdown children={input} sourcePos />)
expect(component.toJSON()).toMatchSnapshot()
})
test('should pass on raw source position to non-tag components if rawSourcePos option is enabled', () => {
const input = '*Foo*\n\n------------\n\n__Bar__'
/**
* @param {Object} props
* @param {Element} props.node
* @param {Position} [props.sourcePosition]
*/
const em = ({node, sourcePosition, ...props}) => {
expect(sourcePosition).toMatchSnapshot()
return <em className="custom" {...props} />
}
const component = renderer.create(
<Markdown children={input} rawSourcePos components={{em}} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should skip nodes that are not defined as allowed', () => {
const input =
'# Header\n\nParagraph\n## New header\n1. List item\n2. List item 2'
const allowed = ['p', 'ol', 'li']
const component = renderer.create(
<Markdown children={input} allowedElements={allowed} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should skip nodes that are defined as disallowed', () => {
const input =
'# Header\n\nParagraph\n## New header\n1. List item\n2. List item 2\n\nFoo'
const component = renderer.create(
<Markdown children={input} disallowedElements={['li']} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should unwrap child nodes from disallowed nodes, if unwrapDisallowed option is enabled', () => {
const input =
'Espen *~~initiated~~ had the initial commit*, but has had several **contributors**'
const component = renderer.create(
<Markdown
children={input}
unwrapDisallowed
disallowedElements={['em', 'strong']}
remarkPlugins={[gfm]}
/>
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should render tables', () => {
const input = [
'Languages are fun, right?',
'',
'| ID | English | Norwegian | Italian |',
'| :-- | :-----: | --------: | ------- |',
'| 1 | one | en | uno |',
'| 2 | two | to | due |',
'| 3 | three | tre | tre |',
''
].join('\n')
expect(
renderHTML(<Markdown children={input} remarkPlugins={[gfm]} />)
).toMatchSnapshot()
})
test('should render partial tables', () => {
const input = 'User is writing a table by hand\n\n| Test | Test |\n|-|-|'
expect(
renderHTML(<Markdown children={input} remarkPlugins={[gfm]} />)
).toMatchSnapshot()
})
test('should render link references', () => {
const input = [
'Stuff were changed in [1.1.4]. Check out the changelog for reference.',
'',
'[1.1.4]: https://github.com/remarkjs/react-markdown/compare/v1.1.3...v1.1.4'
].join('\n')
expect(renderHTML(<Markdown children={input} />)).toMatchSnapshot()
})
test('should render empty link references', () => {
const input =
'Stuff were changed in [][]. Check out the changelog for reference.'
expect(renderHTML(<Markdown children={input} />)).toMatchSnapshot()
})
test('should render image references', () => {
const input = [
'Checkout out this ninja: ![The Waffle Ninja][ninja]. Pretty neat, eh?',
'',
'[ninja]: /assets/ninja.png'
].join('\n')
expect(renderHTML(<Markdown children={input} />)).toMatchSnapshot()
})
test('should support definitions with funky keys', () => {
const input =
'[][__proto__] and [][constructor]\n\n[__proto__]: a\n[constructor]: b'
const actual = renderHTML(
<Markdown children={input} transformLinkUri={null} />
)
const expected = '<p><a href="a"></a> and <a href="b"></a></p>'
expect(actual).toEqual(expected)
})
test('should support duplicate definitions', () => {
const input = '[a][]\n\n[a]: b\n[a]: c'
const actual = renderHTML(
<Markdown children={input} transformLinkUri={null} />
)
const expected = '<p><a href="b">a</a></p>'
expect(actual).toEqual(expected)
})
describe('should skip nodes that are defined as disallowed', () => {
const samples = {
p: {input: 'Paragraphs are cool', shouldNotContain: 'Paragraphs are cool'},
h1: {input: '# Headers are neat', shouldNotContain: 'Headers are neat'},
br: {input: 'Text \nHardbreak', shouldNotContain: '<br/>'},
a: {
input: "[Espen's blog](http://espen.codes/) yeh?",
shouldNotContain: '<a'
},
img: {input: 'Holy ![ninja](/ninja.png), batman', shouldNotContain: '<img'},
em: {input: 'Many *contributors*', shouldNotContain: '<em'},
code: {
input: "```\nvar moo = require('bar');\nmoo();\n```",
shouldNotContain: '<pre><code>'
},
blockquote: {
input: '> Moo\n> Tools\n> FTW\n',
shouldNotContain: '<blockquote'
},
ul: {input: '* A list\n*Of things', shouldNotContain: 'Of things'},
li: {input: '* IPA\n*Imperial Stout\n', shouldNotContain: '<li'},
strong: {input: "Don't **give up**, alright?", shouldNotContain: 'give up'},
hr: {input: '\n-----\nAnd with that...', shouldNotContain: '<hr'}
}
const fullInput = Object.keys(samples)
.map((/** @type {keyof samples} */ key) => samples[key].input)
.join('\n')
// eslint-disable-next-line unicorn/no-array-for-each
Object.keys(samples).forEach((/** @type {keyof samples} */ key) => {
test(key, () => {
/** @type {samples[keyof samples]} */
const sample = samples[key]
expect(
renderHTML(<Markdown children={fullInput} disallowedElements={[key]} />)
).not.toContain(sample.shouldNotContain)
// Just for sanity's sake, let ensure that the opposite is true
expect(renderHTML(<Markdown children={fullInput} />)).toContain(
sample.shouldNotContain
)
})
})
})
test('should throw if both allowed and disallowed types is specified', () => {
expect(() => {
renderHTML(
<Markdown
children=""
allowedElements={['p']}
disallowedElements={['a']}
/>
)
}).toThrow(/only one of/i)
})
test('should be able to use a custom function to determine if the node should be allowed', () => {
const input = [
'# Header',
'[react-markdown](https://github.com/remarkjs/react-markdown/) is a nice helper',
'Also check out [my website](https://espen.codes/)'
].join('\n\n')
/**
* @param {Element} element
*/
const allow = (element) =>
element.tagName !== 'a' ||
(typeof element.properties.href === 'string' &&
element.properties.href.indexOf('https://github.com/') === 0)
expect(
renderHTML(<Markdown children={input} allowElement={allow} />)
).toEqual(
[
'<h1>Header</h1>',
'<p><a href="https://github.com/remarkjs/react-markdown/">react-markdown</a> is a nice helper</p>',
'<p>Also check out </p>'
].join('\n')
)
})
test('should be able to override components', () => {
const input =
'# Header\n\nParagraph\n## New header\n1. List item\n2. List item 2\n\nFoo'
/**
* @param {number} level
*/
const heading = (level) => {
/**
* @param {Object} props
* @param {ReactNode[]} props.children
*/
const component = (props) => (
<span className={`heading level-${level}`}>{props.children}</span>
)
return component
}
const component = renderer.create(
<Markdown children={input} components={{h1: heading(1), h2: heading(2)}} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should throw on invalid component', () => {
const input =
'# Header\n\nParagraph\n## New header\n1. List item\n2. List item 2\n\nFoo'
const components = {h1: 123}
expect(() =>
// @ts-ignore runtime
renderHTML(<Markdown children={input} components={components} />)
).toThrow(/Component for name `h1`/)
})
test('can render the whole spectrum of markdown within a single run', (done) => {
fs.readFile(
path.join(__dirname, 'fixtures', 'runthrough.md'),
'utf8',
(error, fixture) => {
if (error) {
done(error)
return
}
const component = renderer.create(
<Markdown
children={fixture}
remarkPlugins={[gfm]}
rehypePlugins={[raw]}
/>
)
expect(component.toJSON()).toMatchSnapshot()
done()
}
)
})
test('can render the whole spectrum of markdown within a single run (with html parser)', (done) => {
fs.readFile(
path.join(__dirname, 'fixtures', 'runthrough.md'),
'utf8',
(error, fixture) => {
if (error) {
done(error)
return
}
const component = renderer.create(
<Markdown
children={fixture}
remarkPlugins={[gfm]}
rehypePlugins={[raw]}
/>
)
expect(component.toJSON()).toMatchSnapshot()
done()
}
)
})
test('should support math', () => {
/**
* @param {Object} props
* @param {Element} props.node
*/
function handle({node, ...props}) {
if (
Array.isArray(node.properties.className) &&
node.properties.className.includes('math')
) {
return (
// @ts-ignore broken types?
<TeX
block={!node.properties.className.includes('math-inline')}
math={node.children[0].value}
/>
)
}
return React.createElement(node.tagName, props)
}
const input =
'Lift($L$) can be determined by Lift Coefficient ($C_L$) like the following equation.\n\n$$\nL = \\frac{1}{2} \\rho v^2 S C_L\n$$'
const component = render(
<Markdown
children={input}
remarkPlugins={[remarkMath]}
components={{div: handle, span: handle}}
/>
).container.innerHTML
expect(component).toMatchSnapshot()
})
test('sanitizes certain dangerous urls for links by default', () => {
const input = [
'# [Much fun](javascript:alert("foo"))',
"Can be had with [XSS links](vbscript:foobar('test'))",
'> And [other](VBSCRIPT:bap) nonsense... [files](file:///etc/passwd) for instance',
'## [Entities]( javascript:alert("bazinga")) can be tricky, too',
'Regular [links](https://foo.bar) must [be]() allowed',
'[Some ref][xss]',
'[xss]: javascript:alert("foo") "Dangerous stuff"',
'Should allow [mailto](mailto:ex@ample.com) and [tel](tel:13133) links tho',
'Also, [protocol-agnostic](//google.com) should be allowed',
'local [paths](/foo/bar) should be [allowed](foo)',
'allow [weird](?javascript:foo) query strings and [hashes](foo#vbscript:orders)'
].join('\n\n')
const component = renderer.create(<Markdown children={input} />)
expect(component.toJSON()).toMatchSnapshot()
})
test('allows specifying a custom URI-transformer', () => {
const input =
'Received a great [pull request](https://github.com/remarkjs/react-markdown/pull/15) today'
/**
* @param {string} uri
* @returns {string}
*/
const transform = (uri) => uri.replace(/^https?:\/\/github\.com\//i, '/')
const component = renderer.create(
<Markdown children={input} transformLinkUri={transform} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should support turning off the default URI transform', () => {
const input = '[a](data:text/html,<script>alert(1)</script>)'
const actual = renderHTML(
<Markdown children={input} transformLinkUri={null} />
)
const expected =
'<p><a href="data:text/html,%3Cscript%3Ealert(1)%3C/script%3E">a</a></p>'
expect(actual).toEqual(expected)
})
test('can use parser plugins', () => {
const input = 'a ~b~ c'
const component = renderer.create(
<Markdown children={input} remarkPlugins={[gfm]} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('supports checkbox lists', () => {
const input = '- [ ] Foo\n- [x] Bar\n\n---\n\n- Foo\n- Bar'
const component = renderer.create(
<Markdown children={input} remarkPlugins={[gfm]} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should pass index of a node under its parent to components if `includeElementIndex` option is enabled', () => {
const input = 'Foo\n\nBar\n\nBaz'
/**
* @param {Object} props
* @param {Element} props.node
* @param {ReactNode[]} props.children
*/
const p = ({node, ...otherProps}) => {
expect(otherProps).toMatchSnapshot()
return <p>{otherProps.children}</p>
}
const component = renderer.create(
<Markdown children={input} includeElementIndex components={{p}} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should be able to render components with forwardRef in HOC', () => {
/**
* @param {Function} Component
*/
const wrapper = (Component) => {
return React.forwardRef((props, ref) => <Component ref={ref} {...props} />)
}
/**
* @param {Object<string, unknown>} props
*/
// eslint-disable-next-line react/jsx-no-target-blank
const wrapped = (props) => <a {...props} />
const component = renderer.create(
<Markdown components={{a: wrapper(wrapped)}}>
[Link](https://example.com/)
</Markdown>
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should render table of contents plugin', () => {
const input = [
'# Header',
'## Table of Contents',
'## First Section',
'## Second Section',
'### Subsection',
'## Third Section'
].join('\n')
const component = renderer.create(
<Markdown children={input} remarkPlugins={[toc]} />
)
expect(component.toJSON()).toMatchSnapshot()
})
test('should pass `node` as prop to all non-tag/non-fragment components', () => {
const input = "# So, *headers... they're _cool_*\n\n"
/**
* @param {Object} props
* @param {Element} props.node
*/
const h1 = (props) => {
let text = ''
visit(props.node, 'text', (/** @type {Text} */ child) => {
text += child.value
})
return text
}
const component = renderer.create(
<Markdown children={input} components={{h1}} />
)
expect(component.toJSON()).toBe("So, headers... they're cool")
})
test('should support formatting at the start of a GFM tasklist (GH-494)', () => {
const input = '- [ ] *a*'
const actual = renderHTML(<Markdown children={input} remarkPlugins={[gfm]} />)
const expected =
'<ul class="contains-task-list">\n<li class="task-list-item"><input type="checkbox" disabled=""/> <em>a</em></li>\n</ul>'
expect(actual).toEqual(expected)
})