jsonp.test.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. require("./chai.helper");
  2. var domHelper = require("./dom.helper");
  3. var HttpFake = require("./http-fake.helper");
  4. describe("jsonp", function () {
  5. var server = HttpFake.createServer();
  6. // we need to refer to this from the tests, but we allow
  7. // the server to randomly get a port before setting it
  8. var host;
  9. before(function (done) {
  10. domHelper();
  11. server.start(function () {
  12. host = "localhost:" + server.port;
  13. done.apply(null, arguments);
  14. });
  15. });
  16. afterEach(function () {
  17. server.clearFakes();
  18. });
  19. after(function (done) {
  20. server.stop(done);
  21. });
  22. it("should load an external JSONP script with callback in the URI", function (done) {
  23. var expected = { JSONP_LOADED: true };
  24. server.registerFake(
  25. // response config
  26. {
  27. data: function (req) {
  28. var callback = req.query["callback"];
  29. return callback + "(" + JSON.stringify(expected) + ");";
  30. }
  31. },
  32. // request matcher
  33. { path: '/1' }
  34. );
  35. // make chai's expect function available in the execution context
  36. // for the script
  37. window.expect = expect;
  38. // this is the function referenced in the querystring sent
  39. // to the server
  40. window.parseResponse = function (data) {
  41. window.expect(data).to.eql(expected);
  42. done();
  43. };
  44. $.jsonP({
  45. // NB querystring callback set to the function defined above
  46. url: "http://" + host + "/1?callback=window.parseResponse",
  47. error: function (xhr) {
  48. console.log(xhr);
  49. done(new Error("could not load jsonp script"));
  50. }
  51. });
  52. });
  53. it("should load an external JSONP script with anonymous callback", function (done) {
  54. var expected = { JSONP_ANON: true };
  55. server.registerFake(
  56. // response config
  57. {
  58. data: function (req) {
  59. var callback = req.query["callback"];
  60. return callback + "(" + JSON.stringify(expected) + ");";
  61. }
  62. },
  63. // request matcher
  64. {
  65. path: '/2',
  66. // ensure that the callback parameter is set to
  67. // a function name generated by appframework
  68. query: function (reqQuery) {
  69. return /jsonp_callback[\d]{1,}/.test(reqQuery["callback"]);
  70. }
  71. }
  72. );
  73. // make chai's expect function available in the execution context
  74. // for the script
  75. window.expect = expect;
  76. $.jsonP({
  77. url: "http://" + host + "/2?callback=?",
  78. success: function (data) {
  79. window.expect(data).to.eql(expected);
  80. done();
  81. },
  82. error: function (xhr) {
  83. console.log(xhr);
  84. done(new Error("could not load jsonp script"));
  85. }
  86. });
  87. });
  88. });