document-outerhtml/test/ index.js
87 lines
1.7 KiB

  1. import test from 'ava'
  2. import Window from 'window';
  3. import documentOuterHTML from '../src'
  4. function makeDocument(html) {
  5. const window = new Window()
  6. const parser = new window.DOMParser()
  7. const doc = parser.parseFromString(html, 'text/html')
  8. return doc
  9. }
  10. function normalise(html) {
  11. // Remove whitespace around string and between tags.
  12. return html.trim().replace(/>\s+</g, '><')
  13. }
  14. test('should work with only an html node', t => {
  15. const html = `
  16. <html>
  17. <head></head>
  18. <body><p>blub.</p></body>
  19. </html>
  20. `
  21. const doc = makeDocument(html)
  22. t.is(
  23. normalise(documentOuterHTML(doc)),
  24. normalise(html)
  25. )
  26. })
  27. test('should work with comments', t => {
  28. const html = `
  29. <!-- comment before -->
  30. <html>
  31. <head></head>
  32. <body><p>blub.</p></body>
  33. </html>
  34. <!-- comment after -->
  35. `
  36. const doc = makeDocument(html)
  37. t.is(
  38. normalise(documentOuterHTML(doc)),
  39. normalise(html)
  40. )
  41. })
  42. test('should work with doctype', t => {
  43. const html = `
  44. <!DOCTYPE html>
  45. <html>
  46. <head></head>
  47. <body><p>blub.</p></body>
  48. </html>
  49. `
  50. const doc = makeDocument(html)
  51. t.is(
  52. normalise(documentOuterHTML(doc)),
  53. normalise(html)
  54. )
  55. })
  56. test('should work without a documentElement', t => {
  57. const html = `
  58. <!DOCTYPE html>
  59. <!-- some comment -->
  60. `
  61. const doc = makeDocument(html)
  62. // The html (+head&body) element will have been created automatically. Remove it.
  63. doc.removeChild(doc.documentElement)
  64. t.is(
  65. normalise(documentOuterHTML(doc)),
  66. normalise(html)
  67. )
  68. })
  69. test('should even work on a completely empty document', t => {
  70. const html = ``
  71. const doc = makeDocument(html)
  72. // The html (+head&body) element will have been created automatically. Remove it.
  73. doc.removeChild(doc.documentElement)
  74. t.is(
  75. normalise(documentOuterHTML(doc)),
  76. normalise(html)
  77. )
  78. })