peerjs.spec.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { describe, expect, it } from "@jest/globals";
  2. import http from "http";
  3. import expectedJson from "../app.json";
  4. import fetch from "node-fetch";
  5. import * as crypto from "crypto";
  6. import { startServer } from "./utils.ts";
  7. const PORT = "9000";
  8. async function makeRequest() {
  9. return new Promise<object>((resolve, reject) => {
  10. http
  11. .get(`http://localhost:${PORT}/`, (resp) => {
  12. let data = "";
  13. resp.on("data", (chunk) => {
  14. data += chunk;
  15. });
  16. resp.on("end", () => {
  17. resolve(JSON.parse(data));
  18. });
  19. })
  20. .on("error", (err) => {
  21. console.log("Error: " + err.message);
  22. reject(err);
  23. });
  24. });
  25. }
  26. describe("Check bin/peerjs", () => {
  27. it("should return content of app.json file", async () => {
  28. expect.assertions(1);
  29. const ls = await startServer();
  30. try {
  31. const resp = await makeRequest();
  32. expect(resp).toEqual(expectedJson);
  33. } finally {
  34. ls.kill();
  35. }
  36. });
  37. it("should reflect the origin header in CORS by default", async () => {
  38. expect.assertions(1);
  39. const ls = await startServer();
  40. const origin = crypto.randomUUID();
  41. try {
  42. const res = await fetch(`http://localhost:${PORT}/peerjs/id`, {
  43. headers: {
  44. Origin: origin,
  45. },
  46. });
  47. expect(res.headers.get("access-control-allow-origin")).toBe(origin);
  48. } finally {
  49. ls.kill();
  50. }
  51. });
  52. it("should respect the CORS parameters", async () => {
  53. expect.assertions(3);
  54. const origin1 = crypto.randomUUID();
  55. const origin2 = crypto.randomUUID();
  56. const origin3 = crypto.randomUUID();
  57. const ls = await startServer(["--cors", origin1, "--cors", origin2]);
  58. try {
  59. const res1 = await fetch(`http://localhost:${PORT}/peerjs/id`, {
  60. headers: {
  61. Origin: origin1,
  62. },
  63. });
  64. expect(res1.headers.get("access-control-allow-origin")).toBe(origin1);
  65. const res2 = await fetch(`http://localhost:${PORT}/peerjs/id`, {
  66. headers: {
  67. Origin: origin2,
  68. },
  69. });
  70. expect(res2.headers.get("access-control-allow-origin")).toBe(origin2);
  71. const res3 = await fetch(`http://localhost:${PORT}/peerjs/id`, {
  72. headers: {
  73. Origin: origin3,
  74. },
  75. });
  76. expect(res3.headers.get("access-control-allow-origin")).toBe(null);
  77. } finally {
  78. ls.kill();
  79. }
  80. });
  81. });