aboutsummaryrefslogtreecommitdiff
path: root/integration/bunjs-only-snippets/serve.test.ts
blob: 8b785dd25eaeb136aee2f39d454feb9f0923cc04 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { file, serve } from "bun";
import { expect, it } from "bun:test";
import { readFileSync } from "fs";
import { resolve } from "path";

var port = 40000;

it("should work for a hello world", async () => {
  const server = serve({
    port: port++,
    fetch(req) {
      return new Response(`Hello, world!`);
    },
  });
  const response = await fetch(`http://localhost:${server.port}`);
  expect(await response.text()).toBe("Hello, world!");
  server.stop();
});

it("should work for a file", async () => {
  const fixture = resolve(import.meta.dir, "./fetch.js.txt");
  const textToExpect = readFileSync(fixture, "utf-8");

  const server = serve({
    port: port++,
    fetch(req) {
      return new Response(file(fixture));
    },
  });
  const response = await fetch(`http://localhost:${server.port}`);
  expect(await response.text()).toBe(textToExpect);
  server.stop();
});

it("fetch should work with headers", async () => {
  const fixture = resolve(import.meta.dir, "./fetch.js.txt");

  const server = serve({
    port: port++,
    fetch(req) {
      if (req.headers.get("X-Foo") !== "bar") {
        return new Response("X-Foo header not set", { status: 500 });
      }
      return new Response(file(fixture), {
        headers: { "X-Both-Ways": "1" },
      });
    },
  });
  const response = await fetch(`http://localhost:${server.port}`, {
    headers: {
      "X-Foo": "bar",
    },
  });

  expect(response.status).toBe(200);
  expect(response.headers.get("X-Both-Ways")).toBe("1");
  server.stop();
});

var count = 200;
it(`should work for a file ${count} times`, async () => {
  const fixture = resolve(import.meta.dir, "./fetch.js.txt");
  const textToExpect = readFileSync(fixture, "utf-8");
  var ran = 0;
  const server = serve({
    port: port++,
    async fetch(req) {
      return new Response(file(fixture));
    },
  });

  // this gets stuck if run about 200 times awaiting all the promises
  // when the promises are run altogether, instead of one at a time
  // it's hard to say if this only happens here due to some weird stuff with the test runner
  // or if it's "real" issue
  for (let i = 0; i < count; i++) {
    const response = await fetch(`http://localhost:${server.port}`);
    expect(await response.text()).toBe(textToExpect);
  }

  server.stop();
});