escaper.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Load modules
  2. var Lab = require('lab');
  3. var Hoek = require('../lib');
  4. // Declare internals
  5. var internals = {};
  6. // Test shortcuts
  7. var expect = Lab.expect;
  8. var before = Lab.before;
  9. var after = Lab.after;
  10. var describe = Lab.experiment;
  11. var it = Lab.test;
  12. describe('Hoek', function () {
  13. describe('#escapeJavaScript', function () {
  14. it('encodes / characters', function (done) {
  15. var encoded = Hoek.escapeJavaScript('<script>alert(1)</script>');
  16. expect(encoded).to.equal('\\x3cscript\\x3ealert\\x281\\x29\\x3c\\x2fscript\\x3e');
  17. done();
  18. });
  19. it('encodes \' characters', function (done) {
  20. var encoded = Hoek.escapeJavaScript('something(\'param\')');
  21. expect(encoded).to.equal('something\\x28\\x27param\\x27\\x29');
  22. done();
  23. });
  24. it('encodes large unicode characters with the correct padding', function (done) {
  25. var encoded = Hoek.escapeJavaScript(String.fromCharCode(500) + String.fromCharCode(1000));
  26. expect(encoded).to.equal('\\u0500\\u1000');
  27. done();
  28. });
  29. it('doesn\'t throw an exception when passed null', function (done) {
  30. var encoded = Hoek.escapeJavaScript(null);
  31. expect(encoded).to.equal('');
  32. done();
  33. });
  34. });
  35. describe('#escapeHtml', function () {
  36. it('encodes / characters', function (done) {
  37. var encoded = Hoek.escapeHtml('<script>alert(1)</script>');
  38. expect(encoded).to.equal('&lt;script&gt;alert&#x28;1&#x29;&lt;&#x2f;script&gt;');
  39. done();
  40. });
  41. it('encodes < and > as named characters', function (done) {
  42. var encoded = Hoek.escapeHtml('<script><>');
  43. expect(encoded).to.equal('&lt;script&gt;&lt;&gt;');
  44. done();
  45. });
  46. it('encodes large unicode characters', function (done) {
  47. var encoded = Hoek.escapeHtml(String.fromCharCode(500) + String.fromCharCode(1000));
  48. expect(encoded).to.equal('&#500;&#1000;');
  49. done();
  50. });
  51. it('doesn\'t throw an exception when passed null', function (done) {
  52. var encoded = Hoek.escapeHtml(null);
  53. expect(encoded).to.equal('');
  54. done();
  55. });
  56. });
  57. });