|
| 1 | +import { DomSanitizer } from '@angular/platform-browser'; |
| 2 | +import { TestBed } from '@angular/core/testing'; |
| 3 | +import { IgxChatMarkdownService } from './markdown-service'; |
| 4 | +import { MarkdownPipe } from './markdown-pipe'; |
| 5 | +import Spy = jasmine.Spy; |
| 6 | + |
| 7 | +// Mock the Service: We only care that the pipe calls the service and gets an HTML string. |
| 8 | +// We provide a *known* unsafe HTML string to ensure sanitization is working. |
| 9 | +const mockUnsafeHtml = ` |
| 10 | + <pre class="shiki" style="color: var(--shiki-fg);"><code><span style="color: #FF0000;">unsafe</span></code></pre> |
| 11 | + <img src="x" onerror="alert(1)"> |
| 12 | +`; |
| 13 | + |
| 14 | +class MockChatMarkdownService { |
| 15 | + public async parse(_: string): Promise<string> { |
| 16 | + return mockUnsafeHtml; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +describe('MarkdownPipe', () => { |
| 21 | + let pipe: MarkdownPipe; |
| 22 | + let sanitizer: DomSanitizer; |
| 23 | + let bypassSpy: Spy; |
| 24 | + |
| 25 | + beforeEach(() => { |
| 26 | + TestBed.configureTestingModule({ |
| 27 | + providers: [ |
| 28 | + MarkdownPipe, |
| 29 | + { provide: IgxChatMarkdownService, useClass: MockChatMarkdownService }, |
| 30 | + ], |
| 31 | + }); |
| 32 | + |
| 33 | + pipe = TestBed.inject(MarkdownPipe); |
| 34 | + sanitizer = TestBed.inject(DomSanitizer); |
| 35 | + bypassSpy = spyOn(sanitizer, 'bypassSecurityTrustHtml').and.callThrough(); |
| 36 | + }); |
| 37 | + |
| 38 | + it('should be created', () => { |
| 39 | + expect(pipe).toBeTruthy(); |
| 40 | + }); |
| 41 | + |
| 42 | + it('should call the service, sanitize content, and return SafeHtml', async () => { |
| 43 | + await pipe.transform('some markdown'); |
| 44 | + |
| 45 | + expect(bypassSpy).toHaveBeenCalledTimes(1); |
| 46 | + |
| 47 | + const sanitizedString = bypassSpy.calls.mostRecent().args[0]; |
| 48 | + |
| 49 | + expect(sanitizedString).not.toContain('onerror'); |
| 50 | + expect(sanitizedString).toContain('style="color: var(--shiki-fg);"'); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should handle undefined input text', async () => { |
| 54 | + await pipe.transform(undefined); |
| 55 | + expect(sanitizer.bypassSecurityTrustHtml).toHaveBeenCalled(); |
| 56 | + }); |
| 57 | +}); |
0 commit comments