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