escaper.js 2.2 KB

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