javascript / expert
Snippet
Testing Dynamic Content Sanitization against XSS in Svelte Rendering
When components render user-provided HTML, security unit tests must verify that malicious payloads like script injections or inline event attributes are thoroughly sanitized. Testing against rendered DOM containers ensures that unsafe DOM elements are omitted and global scope remains uncompromised.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { render } from '@testing-library/svelte';import { expect, test } from 'vitest';import SecureHTMLRenderer from './SecureHTMLRenderer.svelte';test('strips dangerous inline script tags before injecting dynamic markup', () => {const maliciousInput = '<img src="x" onerror="alert(1)" /><script>window.pwned=true</script>';const { container } = render(SecureHTMLRenderer, {props: { rawContent: maliciousInput }});const scriptTag = container.querySelector('script');const imgTag = container.querySelector('img');expect(scriptTag).toBeNull();expect(imgTag?.getAttribute('onerror')).toBeNull();expect(window.pwned).toBeUndefined();});
svelte
Breakdown
1
const maliciousInput = '<img src="x" onerror="alert(1)" /><script>window.pwned=true</script>';
Defines an aggressive XSS test payload targeting element creation and inline event execution.
2
const { container } = render(SecureHTMLRenderer, { props: { rawContent: maliciousInput } });
Renders the component into a DOM node container to inspect parsed HTML output.
3
expect(scriptTag).toBeNull();
Confirms that script tags were removed prior to DOM mounting.
4
expect(imgTag?.getAttribute('onerror')).toBeNull();
Verifies that event handler attributes were stripped away to prevent arbitrary code execution.