sanitizer.spec.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { DefaultAllowlist, sanitizeHtml } from '../../../src/util/sanitizer'
  2. describe('Sanitizer', () => {
  3. describe('sanitizeHtml', () => {
  4. it('should return the same on empty string', () => {
  5. const empty = ''
  6. const result = sanitizeHtml(empty, DefaultAllowlist, null)
  7. expect(result).toEqual(empty)
  8. })
  9. it('should sanitize template by removing tags with XSS', () => {
  10. const template = [
  11. '<div>',
  12. ' <a href="javascript:alert(7)">Click me</a>',
  13. ' <span>Some content</span>',
  14. '</div>'
  15. ].join('')
  16. const result = sanitizeHtml(template, DefaultAllowlist, null)
  17. expect(result).not.toContain('href="javascript:alert(7)')
  18. })
  19. it('should allow aria attributes and safe attributes', () => {
  20. const template = [
  21. '<div aria-pressed="true">',
  22. ' <span class="test">Some content</span>',
  23. '</div>'
  24. ].join('')
  25. const result = sanitizeHtml(template, DefaultAllowlist, null)
  26. expect(result).toContain('aria-pressed')
  27. expect(result).toContain('class="test"')
  28. })
  29. it('should remove tags not in allowlist', () => {
  30. const template = [
  31. '<div>',
  32. ' <script>alert(7)</script>',
  33. '</div>'
  34. ].join('')
  35. const result = sanitizeHtml(template, DefaultAllowlist, null)
  36. expect(result).not.toContain('<script>')
  37. })
  38. it('should not use native api to sanitize if a custom function passed', () => {
  39. const template = [
  40. '<div>',
  41. ' <span>Some content</span>',
  42. '</div>'
  43. ].join('')
  44. function mySanitize(htmlUnsafe) {
  45. return htmlUnsafe
  46. }
  47. spyOn(DOMParser.prototype, 'parseFromString')
  48. const result = sanitizeHtml(template, DefaultAllowlist, mySanitize)
  49. expect(result).toEqual(template)
  50. expect(DOMParser.prototype.parseFromString).not.toHaveBeenCalled()
  51. })
  52. it('should allow multiple sanitation passes of the same template', () => {
  53. const template = '<img src="test.jpg">'
  54. const firstResult = sanitizeHtml(template, DefaultAllowlist, null)
  55. const secondResult = sanitizeHtml(template, DefaultAllowlist, null)
  56. expect(firstResult).toContain('src')
  57. expect(secondResult).toContain('src')
  58. })
  59. })
  60. })