aboutsummaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rw-r--r--test/bun.js/.prettierignore2
-rw-r--r--test/bun.js/baz.js1
-rw-r--r--test/bun.js/body-stream.test.ts2
-rw-r--r--test/bun.js/buffer.test.js5
-rw-r--r--test/bun.js/bun-server.test.ts120
-rw-r--r--test/bun.js/bun-write.test.js8
-rw-r--r--test/bun.js/disabled-module.test.js94
-rw-r--r--test/bun.js/emptyFile0
-rw-r--r--test/bun.js/event-emitter.test.ts2
-rw-r--r--test/bun.js/fetch.test.js274
-rw-r--r--test/bun.js/fetch_headers.test.js20
-rw-r--r--test/bun.js/fs.test.ts (renamed from test/bun.js/fs.test.js)53
-rw-r--r--test/bun.js/gc.ts (renamed from test/bun.js/gc.js)4
-rw-r--r--test/bun.js/inspect.test.js2
-rw-r--r--test/bun.js/install/bun-install.test.ts124
-rw-r--r--test/bun.js/install/dummy.registry.ts2
-rw-r--r--test/bun.js/install/moo-0.1.0.tgzbin0 -> 197 bytes
-rw-r--r--test/bun.js/node-http.test.ts145
-rw-r--r--test/bun.js/os.test.js9
-rw-r--r--test/bun.js/package.json3
-rw-r--r--test/bun.js/preload-test.test.js227
-rw-r--r--test/bun.js/repro_2005.test.js1
-rw-r--r--test/bun.js/sleep.js2
-rw-r--r--test/bun.js/sleepSync.test.ts32
-rw-r--r--test/bun.js/sqlite.test.js23
-rw-r--r--test/snippets/code-simplification-neql-define.js20
-rw-r--r--test/snippets/export.js5
-rw-r--r--test/snippets/jsx-entities.jsx5
-rw-r--r--test/snippets/latin1-chars-in-regexp.js34
-rw-r--r--test/snippets/optional-chain-with-function.js8
-rw-r--r--test/snippets/package.json3
-rw-r--r--test/snippets/react-context-value-func.tsx2
-rw-r--r--test/snippets/simple-lit-example.ts8
-rw-r--r--test/snippets/spread_with_key.tsx7
-rw-r--r--test/snippets/string-escapes.js34
-rw-r--r--test/snippets/styledcomponents-output.js20
-rw-r--r--test/snippets/template-literal.js15
-rw-r--r--test/snippets/type-only-imports.ts3
38 files changed, 902 insertions, 417 deletions
diff --git a/test/bun.js/.prettierignore b/test/bun.js/.prettierignore
new file mode 100644
index 000000000..91b589eb2
--- /dev/null
+++ b/test/bun.js/.prettierignore
@@ -0,0 +1,2 @@
+node_modules
+third-party
diff --git a/test/bun.js/baz.js b/test/bun.js/baz.js
index 5837bb3bb..58a9bb4b0 100644
--- a/test/bun.js/baz.js
+++ b/test/bun.js/baz.js
@@ -1,2 +1,3 @@
// this file is used in resolve.test.js
+//
export default {};
diff --git a/test/bun.js/body-stream.test.ts b/test/bun.js/body-stream.test.ts
index 9a68ad3bc..1cd932ed9 100644
--- a/test/bun.js/body-stream.test.ts
+++ b/test/bun.js/body-stream.test.ts
@@ -3,7 +3,7 @@ import { file, gc, serve, ServeOptions } from "bun";
import { afterAll, afterEach, describe, expect, it, test } from "bun:test";
import { readFileSync } from "fs";
-var port = 4021;
+var port = 0;
{
const BodyMixin = [
diff --git a/test/bun.js/buffer.test.js b/test/bun.js/buffer.test.js
index 0dcf96816..b8fade4d2 100644
--- a/test/bun.js/buffer.test.js
+++ b/test/bun.js/buffer.test.js
@@ -2552,7 +2552,10 @@ it("should not perform out-of-bound access on invalid UTF-8 byte sequence", () =
});
it("repro #2063", () => {
- const buf = Buffer.from("eyJlbWFpbCI6Ijg3MTg4NDYxN0BxcS5jb20iLCJpZCI6OCwicm9sZSI6Im5vcm1hbCIsImlhdCI6MTY3NjI4NDQyMSwiZXhwIjoxNjc2ODg5MjIxfQ", 'base64');
+ const buf = Buffer.from(
+ "eyJlbWFpbCI6Ijg3MTg4NDYxN0BxcS5jb20iLCJpZCI6OCwicm9sZSI6Im5vcm1hbCIsImlhdCI6MTY3NjI4NDQyMSwiZXhwIjoxNjc2ODg5MjIxfQ",
+ "base64",
+ );
expect(buf.length).toBe(85);
expect(buf[82]).toBe(50);
expect(buf[83]).toBe(49);
diff --git a/test/bun.js/bun-server.test.ts b/test/bun.js/bun-server.test.ts
index d5aae537e..52574d2a3 100644
--- a/test/bun.js/bun-server.test.ts
+++ b/test/bun.js/bun-server.test.ts
@@ -48,4 +48,124 @@ describe("Server", () => {
server.stop(true);
}
});
+
+ test("abort signal on server should only fire if aborted", async () => {
+ {
+ const abortController = new AbortController();
+
+ let signalOnServer = false;
+ const server = Bun.serve({
+ async fetch(req) {
+ req.signal.addEventListener("abort", () => {
+ signalOnServer = true;
+ });
+ return new Response("Hello");
+ },
+ port: 0,
+ });
+
+ try {
+ await fetch(`http://${server.hostname}:${server.port}`, { signal: abortController.signal });
+ } catch {}
+ expect(signalOnServer).toBe(false);
+ server.stop(true);
+ }
+ });
+
+ test("abort signal on server with direct stream", async () => {
+ {
+ let signalOnServer = false;
+ const abortController = new AbortController();
+
+ const server = Bun.serve({
+ async fetch(req) {
+ req.signal.addEventListener("abort", () => {
+ signalOnServer = true;
+ });
+ return new Response(
+ new ReadableStream({
+ type: "direct",
+ async pull(controller) {
+ abortController.abort();
+
+ const buffer = await Bun.file(import.meta.dir + "/fixture.html.gz").arrayBuffer();
+ controller.write(buffer);
+
+ //wait to detect the connection abortion
+ await Bun.sleep(15);
+
+ controller.close();
+ },
+ }),
+ {
+ headers: {
+ "Content-Encoding": "gzip",
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Length": "1",
+ },
+ },
+ );
+ },
+ port: 0,
+ });
+
+ try {
+ await fetch(`http://${server.hostname}:${server.port}`, { signal: abortController.signal });
+ } catch {}
+ await Bun.sleep(10);
+ expect(signalOnServer).toBe(true);
+ server.stop(true);
+ }
+ });
+
+ test("abort signal on server with stream", async () => {
+ {
+ let signalOnServer = false;
+ const abortController = new AbortController();
+
+ const server = Bun.serve({
+ async fetch(req) {
+ req.signal.addEventListener("abort", () => {
+ signalOnServer = true;
+ });
+ return new Response(
+ new ReadableStream({
+ async pull(controller) {
+ console.trace("here");
+ abortController.abort();
+
+ const buffer = await Bun.file(import.meta.dir + "/fixture.html.gz").arrayBuffer();
+ console.trace("here");
+ controller.enqueue(buffer);
+ console.trace("here");
+
+ //wait to detect the connection abortion
+ await Bun.sleep(15);
+ controller.close();
+ },
+ }),
+ {
+ headers: {
+ "Content-Encoding": "gzip",
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Length": "1",
+ },
+ },
+ );
+ },
+ port: 0,
+ });
+
+ try {
+ console.trace("here");
+ await fetch(`http://${server.hostname}:${server.port}`, { signal: abortController.signal });
+ } catch {}
+ await Bun.sleep(10);
+ console.trace("here");
+ expect(signalOnServer).toBe(true);
+ console.trace("here");
+ server.stop(true);
+ console.trace("here");
+ }
+ });
});
diff --git a/test/bun.js/bun-write.test.js b/test/bun.js/bun-write.test.js
index 7e1d43059..c324d36a0 100644
--- a/test/bun.js/bun-write.test.js
+++ b/test/bun.js/bun-write.test.js
@@ -139,6 +139,14 @@ it("Bun.file", async () => {
await gcTick();
});
+it("Bun.file empty file", async () => {
+ const file = path.join(import.meta.dir, "emptyFile");
+ await gcTick();
+ const buffer = await Bun.file(file).arrayBuffer();
+ expect(buffer.byteLength).toBe(0);
+ await gcTick();
+});
+
it("Bun.file as a Blob", async () => {
const filePath = path.join(import.meta.path, "../fetch.js.txt");
const fixture = fs.readFileSync(filePath, "utf8");
diff --git a/test/bun.js/disabled-module.test.js b/test/bun.js/disabled-module.test.js
index c12676959..61411aa44 100644
--- a/test/bun.js/disabled-module.test.js
+++ b/test/bun.js/disabled-module.test.js
@@ -1,38 +1,72 @@
import { expect, test } from "bun:test";
-test("not implemented yet module masquerades as undefined and throws an error", () => {
- const worker_threads = import.meta.require("worker_threads");
+// test("not implemented yet module masquerades as undefined and throws an error", () => {
+// const worker_threads = import.meta.require("worker_threads");
- expect(typeof worker_threads).toBe("undefined");
- expect(typeof worker_threads.getEnvironmentData).toBe("undefined");
+// expect(typeof worker_threads).toBe("undefined");
+// expect(typeof worker_threads.getEnvironmentData).toBe("undefined");
+// });
+
+test("AsyncContext", async done => {
+ const { AsyncContext } = import.meta.require("async_hooks");
+ console.log("here");
+ const ctx = new AsyncContext();
+ ctx
+ .run(1234, async () => {
+ expect(ctx.get()).toBe(1234);
+ console.log("here");
+ await 1;
+ console.log("ctx", ctx.get());
+ const setTimeoutResult = await ctx.run(
+ 2345,
+ () =>
+ new Promise(resolve => {
+ queueMicrotask(() => {
+ console.log("queueMicrotask", ctx.get());
+ resolve(ctx.get());
+ });
+ }),
+ );
+ expect(setTimeoutResult).toBe(2345);
+ expect(ctx.get()).toBe(1234);
+ return "final result";
+ })
+ .then(result => {
+ expect(result).toBe("final result");
+ // The code that generated the Promise has access to the 1234
+ // value provided to ctx.run above, but consumers of the Promise
+ // do not automatically inherit it.
+ expect(ctx.get()).toBeUndefined();
+ done();
+ });
});
-test("AsyncLocalStorage polyfill", () => {
- const { AsyncLocalStorage } = import.meta.require("async_hooks");
+// test("AsyncLocalStorage polyfill", () => {
+// const { AsyncLocalStorage } = import.meta.require("async_hooks");
- const store = new AsyncLocalStorage();
- var called = false;
- expect(store.getStore()).toBe(null);
- store.run({ foo: "bar" }, () => {
- expect(store.getStore()).toEqual({ foo: "bar" });
- called = true;
- });
- expect(store.getStore()).toBe(null);
- expect(called).toBe(true);
-});
+// const store = new AsyncLocalStorage();
+// var called = false;
+// expect(store.getStore()).toBe(null);
+// store.run({ foo: "bar" }, () => {
+// expect(store.getStore()).toEqual({ foo: "bar" });
+// called = true;
+// });
+// expect(store.getStore()).toBe(null);
+// expect(called).toBe(true);
+// });
-test("AsyncResource polyfill", () => {
- const { AsyncResource } = import.meta.require("async_hooks");
+// test("AsyncResource polyfill", () => {
+// const { AsyncResource } = import.meta.require("async_hooks");
- const resource = new AsyncResource("test");
- var called = false;
- resource.runInAsyncScope(
- () => {
- called = true;
- },
- null,
- "foo",
- "bar",
- );
- expect(called).toBe(true);
-});
+// const resource = new AsyncResource("test");
+// var called = false;
+// resource.runInAsyncScope(
+// () => {
+// called = true;
+// },
+// null,
+// "foo",
+// "bar",
+// );
+// expect(called).toBe(true);
+// });
diff --git a/test/bun.js/emptyFile b/test/bun.js/emptyFile
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/test/bun.js/emptyFile
diff --git a/test/bun.js/event-emitter.test.ts b/test/bun.js/event-emitter.test.ts
index cd1eaeaf2..2bb891778 100644
--- a/test/bun.js/event-emitter.test.ts
+++ b/test/bun.js/event-emitter.test.ts
@@ -150,7 +150,7 @@ test("EventEmitter GCs", () => {
(function () {
Bun.gc(true);
- function EventEmitterSubclass() {
+ function EventEmitterSubclass(this: any) {
EventEmitter.call(this);
}
diff --git a/test/bun.js/fetch.test.js b/test/bun.js/fetch.test.js
index 1c27c53a0..be64a0109 100644
--- a/test/bun.js/fetch.test.js
+++ b/test/bun.js/fetch.test.js
@@ -27,115 +27,6 @@ afterEach(() => {
const payload = new Uint8Array(1024 * 1024 * 2);
crypto.getRandomValues(payload);
-describe("AbortSignalStreamTest", async () => {
- async function abortOnStage(body, stage) {
- let error = undefined;
- var abortController = new AbortController();
- {
- const server = getServer({
- async fetch(request) {
- let chunk_count = 0;
- const reader = request.body.getReader();
- return Response(
- new ReadableStream({
- async pull(controller) {
- while (true) {
- chunk_count++;
-
- const { done, value } = await reader.read();
- if (chunk_count == stage) {
- abortController.abort();
- }
-
- if (done) {
- controller.close();
- return;
- }
- controller.enqueue(value);
- }
- },
- }),
- );
- },
- });
-
- try {
- const signal = abortController.signal;
-
- await fetch(`http://127.0.0.1:${server.port}`, { method: "POST", body, signal: signal }).then(res =>
- res.arrayBuffer(),
- );
- } catch (ex) {
- error = ex;
- }
- expect(error.name).toBe("AbortError");
- expect(error.message).toBe("The operation was aborted.");
- expect(error instanceof DOMException).toBeTruthy();
- }
- }
-
- for (let i = 1; i < 7; i++) {
- it(`Abort after ${i} chunks`, async () => {
- await abortOnStage(payload, i);
- });
- }
-});
-
-describe("AbortSignalDirectStreamTest", () => {
- async function abortOnStage(body, stage) {
- let error = undefined;
- var abortController = new AbortController();
- {
- const server = getServer({
- async fetch(request) {
- let chunk_count = 0;
- const reader = request.body.getReader();
- return Response(
- new ReadableStream({
- type: "direct",
- async pull(controller) {
- while (true) {
- chunk_count++;
-
- const { done, value } = await reader.read();
- if (chunk_count == stage) {
- abortController.abort();
- }
-
- if (done) {
- controller.end();
- return;
- }
- controller.write(value);
- }
- },
- }),
- );
- },
- });
-
- try {
- const signal = abortController.signal;
-
- await fetch(`http://127.0.0.1:${server.port}`, { method: "POST", body, signal: signal }).then(res =>
- res.arrayBuffer(),
- );
- } catch (ex) {
- error = ex;
- }
- expect(error.name).toBe("AbortError");
- expect(error.message).toBe("The operation was aborted.");
- expect(error instanceof DOMException).toBeTruthy();
- }
- }
-
- for (let i = 1; i < 7; i++) {
- it(`Abort after ${i} chunks`, async () => {
- await abortOnStage(payload, i);
- });
- }
-});
-
describe("AbortSignal", () => {
var server;
beforeEach(() => {
@@ -523,31 +414,33 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) {
if (withGC) gc();
});
- it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> json${withGC ? " (with gc) " : ""
- }`, async () => {
- if (withGC) gc();
- var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
- if (withGC) gc();
- expect(JSON.stringify(await response.json())).toBe(JSON.stringify(jsonObject));
- if (withGC) gc();
- });
+ it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> json${
+ withGC ? " (with gc) " : ""
+ }`, async () => {
+ if (withGC) gc();
+ var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
+ if (withGC) gc();
+ expect(JSON.stringify(await response.json())).toBe(JSON.stringify(jsonObject));
+ if (withGC) gc();
+ });
- it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> invalid json${withGC ? " (with gc) " : ""
- }`, async () => {
- if (withGC) gc();
- var response = blobbyConstructor(
- new TextEncoder().encode(JSON.stringify(jsonObject) + " NOW WE ARE INVALID JSON"),
- );
- if (withGC) gc();
- var failed = false;
- try {
- await response.json();
- } catch (e) {
- failed = true;
- }
- expect(failed).toBe(true);
- if (withGC) gc();
- });
+ it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> invalid json${
+ withGC ? " (with gc) " : ""
+ }`, async () => {
+ if (withGC) gc();
+ var response = blobbyConstructor(
+ new TextEncoder().encode(JSON.stringify(jsonObject) + " NOW WE ARE INVALID JSON"),
+ );
+ if (withGC) gc();
+ var failed = false;
+ try {
+ await response.json();
+ } catch (e) {
+ failed = true;
+ }
+ expect(failed).toBe(true);
+ if (withGC) gc();
+ });
it(`${jsonObject.hello === true ? "latin1" : "utf16"} text${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
@@ -557,14 +450,15 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) {
if (withGC) gc();
});
- it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> text${withGC ? " (with gc) " : ""
- }`, async () => {
- if (withGC) gc();
- var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
- if (withGC) gc();
- expect(await response.text()).toBe(JSON.stringify(jsonObject));
- if (withGC) gc();
- });
+ it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> text${
+ withGC ? " (with gc) " : ""
+ }`, async () => {
+ if (withGC) gc();
+ var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
+ if (withGC) gc();
+ expect(await response.text()).toBe(JSON.stringify(jsonObject));
+ if (withGC) gc();
+ });
it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer${withGC ? " (with gc) " : ""}`, async () => {
if (withGC) gc();
@@ -589,29 +483,30 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) {
if (withGC) gc();
});
- it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> arrayBuffer${withGC ? " (with gc) " : ""
- }`, async () => {
- if (withGC) gc();
+ it(`${jsonObject.hello === true ? "latin1" : "utf16"} arrayBuffer -> arrayBuffer${
+ withGC ? " (with gc) " : ""
+ }`, async () => {
+ if (withGC) gc();
- var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
- if (withGC) gc();
+ var response = blobbyConstructor(new TextEncoder().encode(JSON.stringify(jsonObject)));
+ if (withGC) gc();
- const bytes = new TextEncoder().encode(JSON.stringify(jsonObject));
- if (withGC) gc();
+ const bytes = new TextEncoder().encode(JSON.stringify(jsonObject));
+ if (withGC) gc();
- const compare = new Uint8Array(await response.arrayBuffer());
- if (withGC) gc();
+ const compare = new Uint8Array(await response.arrayBuffer());
+ if (withGC) gc();
- withoutAggressiveGC(() => {
- for (let i = 0; i < compare.length; i++) {
- if (withGC) gc();
+ withoutAggressiveGC(() => {
+ for (let i = 0; i < compare.length; i++) {
+ if (withGC) gc();
- expect(compare[i]).toBe(bytes[i]);
- if (withGC) gc();
- }
- });
- if (withGC) gc();
+ expect(compare[i]).toBe(bytes[i]);
+ if (withGC) gc();
+ }
});
+ if (withGC) gc();
+ });
hasBlobFn &&
it(`${jsonObject.hello === true ? "latin1" : "utf16"} blob${withGC ? " (with gc) " : ""}`, async () => {
@@ -654,11 +549,12 @@ function testBlobInterface(blobbyConstructor, hasBlobFn) {
describe("Bun.file", () => {
const tempdir = require("os").tmpdir();
+ const { join } = require("path");
var callCount = 0;
testBlobInterface(data => {
const blob = new Blob([data]);
const buffer = Bun.peek(blob.arrayBuffer());
- const path = tempdir + "-" + callCount++ + ".bytes";
+ const path = join(tempdir, "tmp-" + callCount++ + ".bytes");
require("fs").writeFileSync(path, buffer);
const file = Bun.file(path);
expect(blob.size).toBe(file.size);
@@ -668,7 +564,7 @@ describe("Bun.file", () => {
it("size is Infinity on a fifo", () => {
try {
unlinkSync("/tmp/test-fifo");
- } catch (e) { }
+ } catch (e) {}
mkfifo("/tmp/test-fifo");
const { size } = Bun.file("/tmp/test-fifo");
@@ -686,14 +582,14 @@ describe("Bun.file", () => {
beforeAll(async () => {
try {
unlinkSync("/tmp/my-new-file");
- } catch { }
+ } catch {}
await Bun.write("/tmp/my-new-file", "hey");
chmodSync("/tmp/my-new-file", 0o000);
});
afterAll(() => {
try {
unlinkSync("/tmp/my-new-file");
- } catch { }
+ } catch {}
});
forEachMethod(m => () => {
@@ -706,7 +602,7 @@ describe("Bun.file", () => {
beforeAll(() => {
try {
unlinkSync("/tmp/does-not-exist");
- } catch { }
+ } catch {}
});
forEachMethod(m => async () => {
@@ -857,12 +753,6 @@ describe("Response", () => {
expect(response.status).toBe(407);
});
- it("body nullable", () => {
- expect(new Response(null).body).toBeNull();
- expect(new Response(undefined).body).toBeNull();
- expect(new Response().body).toBeNull();
- });
-
it("supports headers", () => {
var response = Response.json("hello", {
headers: {
@@ -978,29 +868,6 @@ describe("Request", () => {
expect(await clone.text()).toBe("<div>hello</div>");
});
- it("body nullable", async () => {
- gc();
- {
- const req = new Request("https://hello.com", { body: null });
- expect(req.body).toBeNull();
- }
- gc();
- {
- const req = new Request("https://hello.com", { body: undefined });
- expect(req.body).toBeNull();
- }
- gc();
- {
- const req = new Request("https://hello.com");
- expect(req.body).toBeNull();
- }
- gc();
- {
- const req = new Request("https://hello.com", { body: "" });
- expect(req.body).toBeNull();
- }
- });
-
it("signal", async () => {
gc();
const controller = new AbortController();
@@ -1059,3 +926,26 @@ describe("Headers", () => {
gc();
});
});
+
+it("body nullable", async () => {
+ gc();
+ {
+ const req = new Request("https://hello.com", { body: null });
+ expect(req.body).toBeNull();
+ }
+ gc();
+ {
+ const req = new Request("https://hello.com", { body: undefined });
+ expect(req.body).toBeNull();
+ }
+ gc();
+ {
+ const req = new Request("https://hello.com");
+ expect(req.body).toBeNull();
+ }
+ gc();
+ {
+ const req = new Request("https://hello.com", { body: "" });
+ expect(req.body).not.toBeNull();
+ }
+});
diff --git a/test/bun.js/fetch_headers.test.js b/test/bun.js/fetch_headers.test.js
index 7f8fab188..2e5b9fa52 100644
--- a/test/bun.js/fetch_headers.test.js
+++ b/test/bun.js/fetch_headers.test.js
@@ -19,17 +19,17 @@ describe("Headers", async () => {
});
it("Headers should work", async () => {
- expect(await fetchContent({"x-test": "header 1"})).toBe("header 1");
+ expect(await fetchContent({ "x-test": "header 1" })).toBe("header 1");
});
it("Header names must be valid", async () => {
- expect(() => fetch(url, {headers: {"a\tb:c": "foo" }})).toThrow("Invalid header name: 'a\tb:c'");
- expect(() => fetch(url, {headers: {"❤️": "foo" }})).toThrow("Invalid header name: '❤️'");
+ expect(() => fetch(url, { headers: { "a\tb:c": "foo" } })).toThrow("Invalid header name: 'a\tb:c'");
+ expect(() => fetch(url, { headers: { "❤️": "foo" } })).toThrow("Invalid header name: '❤️'");
});
it("Header values must be valid", async () => {
- expect(() => fetch(url, {headers: {"x-test": "\0" }})).toThrow("Header 'x-test' has invalid value: '\0'");
- expect(() => fetch(url, {headers: {"x-test": "❤️" }})).toThrow("Header 'x-test' has invalid value: '❤️'");
+ expect(() => fetch(url, { headers: { "x-test": "\0" } })).toThrow("Header 'x-test' has invalid value: '\0'");
+ expect(() => fetch(url, { headers: { "x-test": "❤️" } })).toThrow("Header 'x-test' has invalid value: '❤️'");
});
it("repro 1602", async () => {
@@ -42,17 +42,13 @@ describe("Headers", async () => {
expect(roundTripString).toBe(origString);
// This one will pass
- expect(await fetchContent({"x-test": roundTripString})).toBe(roundTripString);
+ expect(await fetchContent({ "x-test": roundTripString })).toBe(roundTripString);
// This would hang
- expect(await fetchContent({"x-test": origString})).toBe(origString);
+ expect(await fetchContent({ "x-test": origString })).toBe(origString);
});
});
async function fetchContent(headers) {
- const res = await fetch(
- url,
- { headers: headers },
- { verbose: true }
- );
+ const res = await fetch(url, { headers: headers }, { verbose: true });
return await res.text();
}
diff --git a/test/bun.js/fs.test.js b/test/bun.js/fs.test.ts
index ce5209c53..4c847d25a 100644
--- a/test/bun.js/fs.test.js
+++ b/test/bun.js/fs.test.ts
@@ -26,6 +26,9 @@ import fs, {
Dirent,
Stats,
} from "node:fs";
+
+import _promises from "node:fs/promises";
+
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -49,7 +52,7 @@ describe("copyFileSync", () => {
it("should work for files < 128 KB", () => {
const tempdir = `/tmp/fs.test.js/${Date.now()}/1234/hi`;
expect(existsSync(tempdir)).toBe(false);
- expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe(true);
+ expect(tempdir.includes(mkdirSync(tempdir, { recursive: true })!)).toBe(true);
// that don't exist
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js");
@@ -67,7 +70,7 @@ describe("copyFileSync", () => {
it("should work for files > 128 KB ", () => {
const tempdir = `/tmp/fs.test.js/${Date.now()}-1/1234/hi`;
expect(existsSync(tempdir)).toBe(false);
- expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe(true);
+ expect(tempdir.includes(mkdirSync(tempdir, { recursive: true })!)).toBe(true);
var buffer = new Int32Array(128 * 1024);
for (let i = 0; i < buffer.length; i++) {
buffer[i] = i % 256;
@@ -92,7 +95,7 @@ describe("mkdirSync", () => {
it("should create a directory", () => {
const tempdir = `/tmp/fs.test.js/${Date.now()}/1234/hi`;
expect(existsSync(tempdir)).toBe(false);
- expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe(true);
+ expect(tempdir.includes(mkdirSync(tempdir, { recursive: true })!)).toBe(true);
expect(existsSync(tempdir)).toBe(true);
});
});
@@ -135,6 +138,7 @@ it("mkdtempSync, readdirSync, rmdirSync and unlinkSync with non-ascii", () => {
});
it("mkdtempSync() empty name", () => {
+ // @ts-ignore-next-line
const tempdir = mkdtempSync();
expect(existsSync(tempdir)).toBe(true);
writeFileSync(tempdir + "/non-ascii-👍.txt", "hello");
@@ -188,7 +192,7 @@ it("readdirSync throws when given a file path", () => {
try {
readdirSync(import.meta.path);
throw new Error("should not get here");
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.name).toBe("ENOTDIR");
}
});
@@ -197,7 +201,7 @@ it("readdirSync throws when given a path that doesn't exist", () => {
try {
readdirSync(import.meta.path + "/does-not-exist/really");
throw new Error("should not get here");
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.name).toBe("ENOTDIR");
}
});
@@ -206,7 +210,7 @@ it("readdirSync throws when given a file path with trailing slash", () => {
try {
readdirSync(import.meta.path + "/");
throw new Error("should not get here");
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.name).toBe("ENOTDIR");
}
});
@@ -455,7 +459,7 @@ describe("stat", () => {
try {
statSync("/tmp/doesntexist");
throw "statSync should throw";
- } catch (e) {
+ } catch (e: any) {
expect(e.code).toBe("ENOENT");
}
});
@@ -499,8 +503,8 @@ describe("rmdir", () => {
rmdir(path, err => {
try {
expect(err).toBeDefined();
- expect(err.code).toBe("EPERM");
- expect(err.message).toBe("Operation not permitted");
+ expect(err!.code).toBe("EPERM");
+ expect(err!.message).toBe("Operation not permitted");
expect(existsSync(path)).toBe(true);
} catch (e) {
return done(e);
@@ -621,6 +625,7 @@ describe("fs.WriteStream", () => {
});
it("should be constructable", () => {
+ // @ts-ignore-next-line
const stream = new fs.WriteStream("test.txt");
expect(stream instanceof fs.WriteStream).toBe(true);
});
@@ -630,6 +635,7 @@ describe("fs.WriteStream", () => {
mkdirForce(pathToDir);
const path = join(pathToDir, `fs-writestream-test.txt`);
+ // @ts-ignore-next-line
const stream = new fs.WriteStream(path, { flags: "w+" });
stream.write("Test file written successfully");
stream.end();
@@ -645,6 +651,7 @@ describe("fs.WriteStream", () => {
});
it("should work if re-exported by name", () => {
+ // @ts-ignore-next-line
const stream = new WriteStream_("test.txt");
expect(stream instanceof WriteStream_).toBe(true);
expect(stream instanceof WriteStreamStar_).toBe(true);
@@ -652,6 +659,7 @@ describe("fs.WriteStream", () => {
});
it("should work if re-exported by name, called without new", () => {
+ // @ts-ignore-next-line
const stream = WriteStream_("test.txt");
expect(stream instanceof WriteStream_).toBe(true);
expect(stream instanceof WriteStreamStar_).toBe(true);
@@ -659,6 +667,7 @@ describe("fs.WriteStream", () => {
});
it("should work if re-exported, as export * from ...", () => {
+ // @ts-ignore-next-line
const stream = new WriteStreamStar_("test.txt");
expect(stream instanceof WriteStream_).toBe(true);
expect(stream instanceof WriteStreamStar_).toBe(true);
@@ -666,6 +675,7 @@ describe("fs.WriteStream", () => {
});
it("should work if re-exported, as export * from..., called without new", () => {
+ // @ts-ignore-next-line
const stream = WriteStreamStar_("test.txt");
expect(stream instanceof WriteStream_).toBe(true);
expect(stream instanceof WriteStreamStar_).toBe(true);
@@ -676,7 +686,7 @@ describe("fs.WriteStream", () => {
const pathToDir = `${tmpdir()}/${Date.now()}`;
mkdirForce(pathToDir);
const path = join(pathToDir, `fs-writestream-re-exported-test.txt`);
-
+ // @ts-ignore-next-line
const stream = new WriteStream_(path, { flags: "w+" });
stream.write("Test file written successfully");
stream.end();
@@ -698,6 +708,7 @@ describe("fs.ReadStream", () => {
});
it("should be constructable", () => {
+ // @ts-ignore-next-line
const stream = new fs.ReadStream("test.txt");
expect(stream instanceof fs.ReadStream).toBe(true);
});
@@ -711,7 +722,7 @@ describe("fs.ReadStream", () => {
encoding: "utf8",
flag: "w+",
});
-
+ // @ts-ignore-next-line
const stream = new fs.ReadStream(path);
stream.setEncoding("utf8");
stream.on("error", e => {
@@ -731,6 +742,7 @@ describe("fs.ReadStream", () => {
});
it("should work if re-exported by name", () => {
+ // @ts-ignore-next-line
const stream = new ReadStream_("test.txt");
expect(stream instanceof ReadStream_).toBe(true);
expect(stream instanceof ReadStreamStar_).toBe(true);
@@ -738,6 +750,7 @@ describe("fs.ReadStream", () => {
});
it("should work if re-exported by name, called without new", () => {
+ // @ts-ignore-next-line
const stream = ReadStream_("test.txt");
expect(stream instanceof ReadStream_).toBe(true);
expect(stream instanceof ReadStreamStar_).toBe(true);
@@ -745,6 +758,7 @@ describe("fs.ReadStream", () => {
});
it("should work if re-exported as export * from ...", () => {
+ // @ts-ignore-next-line
const stream = new ReadStreamStar_("test.txt");
expect(stream instanceof ReadStreamStar_).toBe(true);
expect(stream instanceof ReadStream_).toBe(true);
@@ -752,6 +766,7 @@ describe("fs.ReadStream", () => {
});
it("should work if re-exported as export * from ..., called without new", () => {
+ // @ts-ignore-next-line
const stream = ReadStreamStar_("test.txt");
expect(stream instanceof ReadStreamStar_).toBe(true);
expect(stream instanceof ReadStream_).toBe(true);
@@ -768,6 +783,7 @@ describe("fs.ReadStream", () => {
flag: "w+",
});
+ // @ts-ignore-next-line
const stream = new ReadStream_(path);
stream.setEncoding("utf8");
stream.on("error", e => {
@@ -812,7 +828,7 @@ describe("createWriteStream", () => {
try {
stream.write(null);
expect(() => {}).toThrow(Error);
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.code).toBe("ERR_STREAM_NULL_VALUES");
}
});
@@ -820,12 +836,13 @@ describe("createWriteStream", () => {
it("writing null throws ERR_STREAM_NULL_VALUES (objectMode: true)", async () => {
const path = `/tmp/fs.test.js/${Date.now()}.createWriteStreamNulls.txt`;
const stream = createWriteStream(path, {
+ // @ts-ignore-next-line
objectMode: true,
});
try {
stream.write(null);
expect(() => {}).toThrow(Error);
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.code).toBe("ERR_STREAM_NULL_VALUES");
}
});
@@ -836,7 +853,7 @@ describe("createWriteStream", () => {
try {
stream.write(false);
expect(() => {}).toThrow(Error);
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.code).toBe("ERR_INVALID_ARG_TYPE");
}
});
@@ -844,12 +861,13 @@ describe("createWriteStream", () => {
it("writing false throws ERR_INVALID_ARG_TYPE (objectMode: true)", async () => {
const path = `/tmp/fs.test.js/${Date.now()}.createWriteStreamFalse.txt`;
const stream = createWriteStream(path, {
+ // @ts-ignore-next-line
objectMode: true,
});
try {
stream.write(false);
expect(() => {}).toThrow(Error);
- } catch (exception) {
+ } catch (exception: any) {
expect(exception.code).toBe("ERR_INVALID_ARG_TYPE");
}
});
@@ -893,7 +911,7 @@ describe("fs/promises", () => {
for (const args of fizz) {
try {
// check it doens't segfault when called with invalid arguments
- await promises.readdir(...args);
+ await promises.readdir(...(args as [any, ...any[]]));
} catch (e) {
// check that producing the error doesn't cause any crashes
Bun.inspect(e);
@@ -909,7 +927,7 @@ describe("fs/promises", () => {
try {
await rmdir(path);
expect(() => {}).toThrow();
- } catch (err) {
+ } catch (err: any) {
expect(err.code).toBe("ENOTDIR");
// expect(err.message).toBe("Operation not permitted");
expect(await exists(path)).toBe(true);
@@ -992,6 +1010,7 @@ it("fs.Stats", () => {
it("repro 1516: can use undefined/null to specify default flag", () => {
const path = "/tmp/repro_1516.txt";
writeFileSync(path, "b", { flag: undefined });
+ // @ts-ignore-next-line
expect(readFileSync(path, { encoding: "utf8", flag: null })).toBe("b");
rmSync(path);
});
diff --git a/test/bun.js/gc.js b/test/bun.js/gc.ts
index 3f9678f92..b9d80116d 100644
--- a/test/bun.js/gc.js
+++ b/test/bun.js/gc.ts
@@ -1,5 +1,5 @@
-export function gc() {
- Bun.gc(true);
+export function gc(force: boolean = true) {
+ Bun.gc(force);
}
// we must ensure that finalizers are run
diff --git a/test/bun.js/inspect.test.js b/test/bun.js/inspect.test.js
index 243f23cdc..024a976a3 100644
--- a/test/bun.js/inspect.test.js
+++ b/test/bun.js/inspect.test.js
@@ -275,7 +275,7 @@ const fixture = [
}),
() => require("events"),
() => {
- return new import.meta.require("events").EventEmitter();
+ return new (import.meta.require("events").EventEmitter)();
},
async () => await import("node:assert"),
async () => await import("./empty.js"),
diff --git a/test/bun.js/install/bun-install.test.ts b/test/bun.js/install/bun-install.test.ts
index 6f7a13433..1fb015a59 100644
--- a/test/bun.js/install/bun-install.test.ts
+++ b/test/bun.js/install/bun-install.test.ts
@@ -1304,6 +1304,108 @@ it("should not hoist if name collides with alias", async () => {
await access(join(package_dir, "bun.lockb"));
});
+it("should handle unscoped alias on scoped dependency", async () => {
+ const urls: string[] = [];
+ setHandler(dummyRegistry(urls, { "0.1.0": {} }));
+ await writeFile(
+ join(package_dir, "package.json"),
+ JSON.stringify({
+ name: "foo",
+ version: "0.0.1",
+ dependencies: {
+ "@barn/moo": "latest",
+ moo: "npm:@barn/moo",
+ },
+ }),
+ );
+ const { stdout, stderr, exited } = spawn({
+ cmd: [bunExe(), "install", "--config", import.meta.dir + "/basic.toml"],
+ cwd: package_dir,
+ stdout: null,
+ stdin: "pipe",
+ stderr: "pipe",
+ env,
+ });
+ expect(stderr).toBeDefined();
+ const err = await new Response(stderr).text();
+ expect(err).toContain("Saved lockfile");
+ expect(stdout).toBeDefined();
+ const out = await new Response(stdout).text();
+ expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([
+ " + @barn/moo@0.1.0",
+ " + moo@0.1.0",
+ "",
+ " 1 packages installed",
+ ]);
+ expect(await exited).toBe(0);
+ expect(urls.sort()).toEqual([`${root_url}/@barn/moo`, `${root_url}/@barn/moo-0.1.0.tgz`]);
+ expect(requested).toBe(2);
+ expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "@barn", "moo"]);
+ expect(await readdirSorted(join(package_dir, "node_modules", "@barn"))).toEqual(["moo"]);
+ expect(await readdirSorted(join(package_dir, "node_modules", "@barn", "moo"))).toEqual(["package.json"]);
+ expect(await file(join(package_dir, "node_modules", "moo", "package.json")).json()).toEqual({
+ name: "@barn/moo",
+ version: "0.1.0",
+ });
+ expect(await readdirSorted(join(package_dir, "node_modules", "moo"))).toEqual(["package.json"]);
+ expect(await file(join(package_dir, "node_modules", "moo", "package.json")).json()).toEqual({
+ name: "@barn/moo",
+ version: "0.1.0",
+ });
+ await access(join(package_dir, "bun.lockb"));
+});
+
+it("should handle scoped alias on unscoped dependency", async () => {
+ const urls: string[] = [];
+ setHandler(dummyRegistry(urls));
+ await writeFile(
+ join(package_dir, "package.json"),
+ JSON.stringify({
+ name: "foo",
+ version: "0.0.1",
+ dependencies: {
+ "@baz/bar": "npm:bar",
+ bar: "latest",
+ },
+ }),
+ );
+ const { stdout, stderr, exited } = spawn({
+ cmd: [bunExe(), "install", "--config", import.meta.dir + "/basic.toml"],
+ cwd: package_dir,
+ stdout: null,
+ stdin: "pipe",
+ stderr: "pipe",
+ env,
+ });
+ expect(stderr).toBeDefined();
+ const err = await new Response(stderr).text();
+ expect(err).toContain("Saved lockfile");
+ expect(stdout).toBeDefined();
+ const out = await new Response(stdout).text();
+ expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([
+ " + @baz/bar@0.0.2",
+ " + bar@0.0.2",
+ "",
+ " 1 packages installed",
+ ]);
+ expect(await exited).toBe(0);
+ expect(urls.sort()).toEqual([`${root_url}/bar`, `${root_url}/bar-0.0.2.tgz`]);
+ expect(requested).toBe(2);
+ expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "@baz", "bar"]);
+ expect(await readdirSorted(join(package_dir, "node_modules", "@baz"))).toEqual(["bar"]);
+ expect(await readdirSorted(join(package_dir, "node_modules", "@baz", "bar"))).toEqual(["package.json"]);
+ expect(await file(join(package_dir, "node_modules", "@baz", "bar", "package.json")).json()).toEqual({
+ name: "bar",
+ version: "0.0.2",
+ });
+ expect(await readdirSorted(join(package_dir, "node_modules", "bar"))).toEqual(["package.json"]);
+ expect(await file(join(package_dir, "node_modules", "bar", "package.json")).json()).toEqual({
+ name: "bar",
+ version: "0.0.2",
+ });
+ await access(join(package_dir, "bun.lockb"));
+});
+
it("should handle GitHub URL in dependencies (user/repo)", async () => {
const urls: string[] = [];
setHandler(dummyRegistry(urls));
@@ -2440,11 +2542,11 @@ it("should prefer optionalDependencies over dependencies of the same name", asyn
name: "foo",
version: "0.0.1",
dependencies: {
- "baz": "0.0.5",
+ baz: "0.0.5",
},
optionalDependencies: {
- "baz": "0.0.3",
- }
+ baz: "0.0.3",
+ },
}),
);
const { stdout, stderr, exited } = spawn({
@@ -2466,10 +2568,7 @@ it("should prefer optionalDependencies over dependencies of the same name", asyn
" 1 packages installed",
]);
expect(await exited).toBe(0);
- expect(urls.sort()).toEqual([
- `${root_url}/baz`,
- `${root_url}/baz-0.0.3.tgz`,
- ]);
+ expect(urls.sort()).toEqual([`${root_url}/baz`, `${root_url}/baz-0.0.3.tgz`]);
expect(requested).toBe(2);
expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "baz"]);
expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["index.js", "package.json"]);
@@ -2496,11 +2595,11 @@ it("should prefer dependencies over peerDependencies of the same name", async ()
name: "foo",
version: "0.0.1",
dependencies: {
- "baz": "0.0.5",
+ baz: "0.0.5",
},
peerDependencies: {
- "baz": "0.0.3",
- }
+ baz: "0.0.3",
+ },
}),
);
const { stdout, stderr, exited } = spawn({
@@ -2522,10 +2621,7 @@ it("should prefer dependencies over peerDependencies of the same name", async ()
" 1 packages installed",
]);
expect(await exited).toBe(0);
- expect(urls.sort()).toEqual([
- `${root_url}/baz`,
- `${root_url}/baz-0.0.5.tgz`,
- ]);
+ expect(urls.sort()).toEqual([`${root_url}/baz`, `${root_url}/baz-0.0.5.tgz`]);
expect(requested).toBe(2);
expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "baz"]);
expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["index.js", "package.json"]);
diff --git a/test/bun.js/install/dummy.registry.ts b/test/bun.js/install/dummy.registry.ts
index bc4554a47..a0a215db8 100644
--- a/test/bun.js/install/dummy.registry.ts
+++ b/test/bun.js/install/dummy.registry.ts
@@ -19,7 +19,7 @@ export function dummyRegistry(urls, info: any = { "0.0.2": {} }) {
);
expect(request.headers.get("npm-auth-type")).toBe(null);
expect(await request.text()).toBe("");
- const name = request.url.slice(request.url.lastIndexOf("/") + 1);
+ const name = request.url.slice(request.url.indexOf("/", root_url.length) + 1);
const versions = {};
let version;
for (version in info) {
diff --git a/test/bun.js/install/moo-0.1.0.tgz b/test/bun.js/install/moo-0.1.0.tgz
new file mode 100644
index 000000000..72efff27b
--- /dev/null
+++ b/test/bun.js/install/moo-0.1.0.tgz
Binary files differ
diff --git a/test/bun.js/node-http.test.ts b/test/bun.js/node-http.test.ts
index 3ba383c2e..7818fba62 100644
--- a/test/bun.js/node-http.test.ts
+++ b/test/bun.js/node-http.test.ts
@@ -81,6 +81,7 @@ describe("node:http", () => {
describe("request", () => {
let server;
+ let serverPort;
let timer = null;
beforeAll(() => {
server = createServer((req, res) => {
@@ -89,7 +90,7 @@ describe("node:http", () => {
if (reqUrl.pathname === "/redirect") {
// Temporary redirect
res.writeHead(301, {
- Location: "http://localhost:8126/redirected",
+ Location: `http://localhost:${serverPort}/redirected`,
});
res.end("Got redirect!\n");
return;
@@ -137,7 +138,9 @@ describe("node:http", () => {
res.end("Hello World");
}
});
- server.listen(8126);
+ server.listen({ port: 0 }, (_, __, port) => {
+ serverPort = port;
+ });
});
afterAll(() => {
server.close();
@@ -145,7 +148,7 @@ describe("node:http", () => {
});
it("should make a standard GET request when passed string as first arg", done => {
- const req = request("http://localhost:8126", res => {
+ const req = request(`http://localhost:${serverPort}`, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -160,8 +163,24 @@ describe("node:http", () => {
req.end();
});
+ it("should make a https:// GET request when passed string as first arg", done => {
+ const req = request("https://example.com", res => {
+ let data = "";
+ res.setEncoding("utf8");
+ res.on("data", chunk => {
+ data += chunk;
+ });
+ res.on("end", () => {
+ expect(data).toContain("This domain is for use in illustrative examples in documents");
+ done();
+ });
+ res.on("error", err => done(err));
+ });
+ req.end();
+ });
+
it("should make a POST request when provided POST method, even without a body", done => {
- const req = request({ host: "localhost", port: 8126, method: "POST" }, res => {
+ const req = request({ host: "localhost", port: serverPort, method: "POST" }, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -177,7 +196,7 @@ describe("node:http", () => {
});
it("should correctly handle a POST request with a body", done => {
- const req = request({ host: "localhost", port: 8126, method: "POST" }, res => {
+ const req = request({ host: "localhost", port: serverPort, method: "POST" }, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -194,7 +213,7 @@ describe("node:http", () => {
});
it("should noop request.setSocketKeepAlive without error", () => {
- const req = request("http://localhost:8126");
+ const req = request(`http://localhost:${serverPort}`);
req.setSocketKeepAlive(true, 1000);
req.end();
expect(true).toBe(true);
@@ -209,7 +228,7 @@ describe("node:http", () => {
const req1 = request(
{
host: "localhost",
- port: 8126,
+ port: serverPort,
path: "/timeout",
timeout: 500,
},
@@ -222,7 +241,7 @@ describe("node:http", () => {
const req2 = request(
{
host: "localhost",
- port: 8126,
+ port: serverPort,
path: "/timeout",
},
res => {
@@ -242,7 +261,7 @@ describe("node:http", () => {
const req1Done = createDone();
const req2Done = createDone();
- const req1 = request("http://localhost:8126/pathTest", res => {
+ const req1 = request(`http://localhost:${serverPort}/pathTest`, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -255,7 +274,7 @@ describe("node:http", () => {
res.on("error", err => req1Done(err));
});
- const req2 = request("http://localhost:8126", { path: "/pathTest" }, res => {
+ const req2 = request(`http://localhost:${serverPort}`, { path: "/pathTest" }, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -276,7 +295,7 @@ describe("node:http", () => {
});
it("should emit response when response received", done => {
- const req = request("http://localhost:8126");
+ const req = request(`http://localhost:${serverPort}`);
req.on("response", res => {
expect(res.statusCode).toBe(200);
@@ -287,7 +306,7 @@ describe("node:http", () => {
// NOTE: Node http.request doesn't follow redirects by default
it("should handle redirects properly", done => {
- const req = request("http://localhost:8126/redirect", res => {
+ const req = request(`http://localhost:${serverPort}/redirect`, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -303,7 +322,7 @@ describe("node:http", () => {
});
it("should correctly attach headers to request", done => {
- const req = request({ host: "localhost", port: 8126, headers: { "X-Test": "test" } }, res => {
+ const req = request({ host: "localhost", port: serverPort, headers: { "X-Test": "test" } }, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -320,7 +339,7 @@ describe("node:http", () => {
});
it("should correct casing of method param", done => {
- const req = request({ host: "localhost", port: 8126, method: "get" }, res => {
+ const req = request({ host: "localhost", port: serverPort, method: "get" }, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -336,7 +355,7 @@ describe("node:http", () => {
});
it("should allow for port as a string", done => {
- const req = request({ host: "localhost", port: "8126", method: "GET" }, res => {
+ const req = request({ host: "localhost", port: `${serverPort}`, method: "GET" }, res => {
let data = "";
res.setEncoding("utf8");
res.on("data", chunk => {
@@ -350,10 +369,51 @@ describe("node:http", () => {
});
req.end();
});
+
+ it("should allow us to pass a URL object", done => {
+ const req = request(new URL(`http://localhost:${serverPort}`), { method: "POST" }, res => {
+ let data = "";
+ res.setEncoding("utf8");
+ res.on("data", chunk => {
+ data += chunk;
+ });
+ res.on("end", () => {
+ expect(data).toBe("Hello WorldPOST\nHello World");
+ done();
+ });
+ res.on("error", err => done(err));
+ });
+ req.write("Hello World");
+ req.end();
+ });
+
+ it("should ignore body when method is GET/HEAD/OPTIONS", done => {
+ const createDone = createDoneDotAll(done);
+ const methods = ["GET", "HEAD", "OPTIONS"];
+ const dones = {};
+ for (const method of methods) {
+ dones[method] = createDone();
+ }
+ for (const method of methods) {
+ const req = request(`http://localhost:${serverPort}`, { method }, res => {
+ let data = "";
+ res.setEncoding("utf8");
+ res.on("data", chunk => {
+ data += chunk;
+ });
+ res.on("end", () => {
+ expect(data).toBe(method === "GET" ? "Maybe GET maybe not\nHello World" : "");
+ dones[method]();
+ });
+ res.on("error", err => dones[method](err));
+ });
+ req.write("BODY");
+ req.end();
+ }
+ });
});
describe("signal", () => {
-
it("should abort and close the server", done => {
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
@@ -361,19 +421,19 @@ describe("node:http", () => {
});
//force timeout to not hang tests
- const interval = setTimeout(()=> {
+ const interval = setTimeout(() => {
expect(false).toBe(true);
server.close();
- done()
+ done();
}, 100);
-
+
const signal = AbortSignal.timeout(30);
- signal.addEventListener("abort", ()=> {
+ signal.addEventListener("abort", () => {
clearTimeout(interval);
expect(true).toBe(true);
- done()
+ done();
});
-
+
server.listen({ signal, port: 8130 });
});
});
@@ -457,4 +517,45 @@ describe("node:http", () => {
expect(globalAgent instanceof Agent).toBe(true);
});
});
+
+ describe("ClientRequest.signal", () => {
+ let server;
+ let server_port;
+ let server_host;
+ beforeAll(() => {
+ server = createServer((req, res) => {
+ Bun.sleep(10).then(() => {
+ res.writeHead(200, { "Content-Type": "text/plain" });
+ res.end("Hello World");
+ });
+ });
+ server.listen({ port: 0 }, (_err, host, port) => {
+ server_port = port;
+ server_host = host;
+ });
+ });
+ afterAll(() => {
+ server.close();
+ });
+ it("should attempt to make a standard GET request and abort", done => {
+ get(`http://127.0.0.1:${server_port}`, { signal: AbortSignal.timeout(5) }, res => {
+ let data = "";
+ res.setEncoding("utf8");
+ res.on("data", chunk => {
+ data += chunk;
+ });
+ res.on("end", () => {
+ expect(true).toBeFalsy();
+ done();
+ });
+ res.on("error", _ => {
+ expect(true).toBeFalsy();
+ done();
+ });
+ }).on("error", err => {
+ expect(err?.name).toBe("AbortError");
+ done();
+ });
+ });
+ });
});
diff --git a/test/bun.js/os.test.js b/test/bun.js/os.test.js
index 122969337..ea685cdb7 100644
--- a/test/bun.js/os.test.js
+++ b/test/bun.js/os.test.js
@@ -42,7 +42,11 @@ it("tmpdir", () => {
expect(os.tmpdir()).toBe(process.env.TEMP || process.env.TMP);
expect(os.tmpdir()).toBe(`${process.env.SystemRoot || process.env.windir}\\temp`);
} else {
- expect(os.tmpdir()).toBe(process.env.TMPDIR || process.env.TMP || process.env.TEMP || "/tmp");
+ let dir = process.env.TMPDIR || process.env.TMP || process.env.TEMP || "/tmp";
+ if (dir.length > 1 && dir.endsWith("/")) {
+ dir = dir.substring(0, dir.length - 1);
+ }
+ expect(os.tmpdir()).toBe(dir);
}
});
@@ -110,7 +114,8 @@ it("networkInterfaces", () => {
expect(typeof nI.family === "string").toBe(true);
expect(typeof nI.mac === "string").toBe(true);
expect(typeof nI.internal === "boolean").toBe(true);
- if (nI.cidr) // may be null
+ if (nI.cidr)
+ // may be null
expect(typeof nI.cidr).toBe("string");
}
}
diff --git a/test/bun.js/package.json b/test/bun.js/package.json
index 4b47715bb..709dc6602 100644
--- a/test/bun.js/package.json
+++ b/test/bun.js/package.json
@@ -5,5 +5,6 @@
"uuid": "^9.0.0",
"tiny-typed-emitter": "^1.0.0",
"svelte": "^3.52.0"
- }
+ },
+ "prettier": "../../.prettierrc.cjs"
}
diff --git a/test/bun.js/preload-test.test.js b/test/bun.js/preload-test.test.js
new file mode 100644
index 000000000..76603b3a0
--- /dev/null
+++ b/test/bun.js/preload-test.test.js
@@ -0,0 +1,227 @@
+import { spawnSync } from "bun";
+import { describe, expect, test } from "bun:test";
+import { mkdirSync, realpathSync } from "fs";
+import { tmpdir } from "os";
+import { join } from "path";
+import { bunEnv } from "./bunEnv";
+import { bunExe } from "./bunExe";
+const preloadModule = `
+import {plugin} from 'bun';
+
+plugin({
+ setup(build) {
+ build.onResolve({ filter: /.*\.txt$/, }, async (args) => {
+ return {
+ path: args.path,
+ namespace: 'boop'
+ }
+ });
+ build.onResolve({ namespace: "boop", filter: /.*/ }, async (args) => {
+ return {
+ path: args.path,
+ namespace: 'boop'
+ }
+ });
+ build.onLoad({ namespace: "boop", filter: /.*/ }, async (args) => {
+ return {
+ contents: '"hello world"',
+ loader: 'json'
+ }
+ });
+ }
+});
+ `;
+
+const mainModule = `
+ import hey from './hey.txt';
+
+ if (hey !== 'hello world') {
+ throw new Error('preload test failed');
+ }
+
+ console.log('Test passed');
+ process.exit(0);
+`;
+
+const bunfig = `preload = ["./preload.js"]`;
+
+describe("preload", () => {
+ test("works", async () => {
+ const preloadDir = join(realpathSync(tmpdir()), "bun-preload-test");
+ mkdirSync(preloadDir, { recursive: true });
+ const preloadPath = join(preloadDir, "preload.js");
+ const mainPath = join(preloadDir, "main.js");
+ const bunfigPath = join(preloadDir, "bunfig.toml");
+ await Bun.write(preloadPath, preloadModule);
+ await Bun.write(mainPath, mainModule);
+ await Bun.write(bunfigPath, bunfig);
+
+ const cmds = [
+ [bunExe(), "run", mainPath],
+ [bunExe(), mainPath],
+ ];
+
+ for (let cmd of cmds) {
+ const { stderr, exitCode, stdout } = spawnSync({
+ cmd,
+ cwd: preloadDir,
+ stderr: "pipe",
+ stdout: "pipe",
+ env: bunEnv,
+ });
+
+ expect(exitCode).toBe(0);
+ expect(stderr.toString()).toBe("");
+ expect(stdout.toString()).toContain("Test passed");
+ }
+ });
+
+ test("works from CLI", async () => {
+ const preloadDir = join(realpathSync(tmpdir()), "bun-preload-test4");
+ mkdirSync(preloadDir, { recursive: true });
+ const preloadPath = join(preloadDir, "preload.js");
+ const mainPath = join(preloadDir, "main.js");
+ await Bun.write(preloadPath, preloadModule);
+ await Bun.write(mainPath, mainModule);
+
+ const cmds = [
+ [bunExe(), "-r=" + preloadPath, "run", mainPath],
+ [bunExe(), "-r=" + preloadPath, mainPath],
+ ];
+
+ for (let cmd of cmds) {
+ const { stderr, exitCode, stdout } = spawnSync({
+ cmd,
+ cwd: preloadDir,
+ stderr: "pipe",
+ stdout: "pipe",
+ env: bunEnv,
+ });
+
+ expect(exitCode).toBe(0);
+ expect(stderr.toString()).toBe("");
+ expect(stdout.toString()).toContain("Test passed");
+ }
+ });
+
+ describe("as entry point", () => {
+ const preloadModule = `
+import {plugin} from 'bun';
+
+plugin({
+ setup(build) {
+ build.onResolve({ filter: /.*\.txt$/, }, async (args) => {
+ return {
+ path: args.path,
+ namespace: 'boop'
+ }
+ });
+ build.onResolve({ namespace: "boop", filter: /.*/ }, async (args) => {
+ return {
+ path: args.path,
+ namespace: 'boop'
+ }
+ });
+ build.onLoad({ namespace: "boop", filter: /.*/ }, async (args) => {
+ return {
+ contents: 'console.log("Test passed")',
+ loader: 'js'
+ }
+ });
+ }
+});
+ `;
+
+ test("works from CLI", async () => {
+ const preloadDir = join(realpathSync(tmpdir()), "bun-preload-test6");
+ mkdirSync(preloadDir, { recursive: true });
+ const preloadPath = join(preloadDir, "preload.js");
+ const mainPath = join(preloadDir, "boop.txt");
+ await Bun.write(preloadPath, preloadModule);
+ await Bun.write(mainPath, "beep");
+
+ const cmds = [
+ [bunExe(), "-r=" + preloadPath, "run", mainPath],
+ [bunExe(), "-r=" + preloadPath, mainPath],
+ ];
+
+ for (let cmd of cmds) {
+ const { stderr, exitCode, stdout } = spawnSync({
+ cmd,
+ cwd: preloadDir,
+ stderr: "pipe",
+ stdout: "pipe",
+ env: bunEnv,
+ });
+
+ expect(stderr.toString()).toBe("");
+ expect(stdout.toString()).toContain("Test passed");
+ expect(exitCode).toBe(0);
+ }
+ });
+ });
+
+ test("throws an error when preloaded module fails to execute", async () => {
+ const preloadModule = "throw new Error('preload test failed');";
+
+ const preloadDir = join(realpathSync(tmpdir()), "bun-preload-test3");
+ mkdirSync(preloadDir, { recursive: true });
+ const preloadPath = join(preloadDir, "preload.js");
+ const mainPath = join(preloadDir, "main.js");
+ const bunfigPath = join(preloadDir, "bunfig.toml");
+ await Bun.write(preloadPath, preloadModule);
+ await Bun.write(mainPath, mainModule);
+ await Bun.write(bunfigPath, bunfig);
+
+ const cmds = [
+ [bunExe(), "run", mainPath],
+ [bunExe(), mainPath],
+ ];
+
+ for (let cmd of cmds) {
+ const { stderr, exitCode, stdout } = spawnSync({
+ cmd,
+ cwd: preloadDir,
+ stderr: "pipe",
+ stdout: "pipe",
+ env: bunEnv,
+ });
+
+ expect(stderr.toString()).toContain("preload test failed");
+ expect(stdout.toString()).toBe("");
+ expect(exitCode).toBe(1);
+ }
+ });
+
+ test("throws an error when preloaded module not found", async () => {
+ const bunfig = `preload = ["./bad-file.js"]`;
+
+ const preloadDir = join(realpathSync(tmpdir()), "bun-preload-test2");
+ mkdirSync(preloadDir, { recursive: true });
+ const preloadPath = join(preloadDir, "preload.js");
+ const mainPath = join(preloadDir, "main.js");
+ const bunfigPath = join(preloadDir, "bunfig.toml");
+ await Bun.write(preloadPath, preloadModule);
+ await Bun.write(mainPath, mainModule);
+ await Bun.write(bunfigPath, bunfig);
+
+ const cmds = [
+ [bunExe(), "run", mainPath],
+ [bunExe(), mainPath],
+ ];
+
+ for (let cmd of cmds) {
+ const { stderr, exitCode, stdout } = spawnSync({
+ cmd,
+ cwd: preloadDir,
+ stderr: "pipe",
+ stdout: "pipe",
+ env: bunEnv,
+ });
+
+ expect(stderr.toString()).toContain("preload not found ");
+ expect(stdout.toString()).toBe("");
+ expect(exitCode).toBe(1);
+ }
+ });
+});
diff --git a/test/bun.js/repro_2005.test.js b/test/bun.js/repro_2005.test.js
index bd80ab7dd..dc0cd9a97 100644
--- a/test/bun.js/repro_2005.test.js
+++ b/test/bun.js/repro_2005.test.js
@@ -8,5 +8,4 @@ it("regex literal with non-Latin1 should work", () => {
//Incorrect result: 这是一段要替换的文字
expect(text.replace(/要替换/, "")).toBe("这是一段的文字");
-
});
diff --git a/test/bun.js/sleep.js b/test/bun.js/sleep.js
index 080597424..1ec79e79d 100644
--- a/test/bun.js/sleep.js
+++ b/test/bun.js/sleep.js
@@ -1,4 +1,4 @@
-const interval = 0.01;
+const interval = 10;
const now = performance.now();
console.time("Slept");
Bun.sleepSync(interval);
diff --git a/test/bun.js/sleepSync.test.ts b/test/bun.js/sleepSync.test.ts
new file mode 100644
index 000000000..dd2e8818a
--- /dev/null
+++ b/test/bun.js/sleepSync.test.ts
@@ -0,0 +1,32 @@
+import { it, expect } from "bun:test";
+import { sleepSync } from "bun";
+
+it("sleepSync uses milliseconds", async () => {
+ const start = Date.now();
+ sleepSync(5);
+ const end = Date.now();
+ expect(end - start).toBeGreaterThanOrEqual(5);
+ expect(end - start).toBeLessThan(10);
+});
+
+it("sleepSync with no arguments throws", async () => {
+ expect(() => sleepSync()).toThrow();
+});
+
+it("sleepSync with non-numbers throws", async () => {
+ expect(() => sleepSync(true)).toThrow();
+ expect(() => sleepSync(false)).toThrow();
+ expect(() => sleepSync("hi")).toThrow();
+ expect(() => sleepSync({})).toThrow();
+ expect(() => sleepSync([])).toThrow();
+ expect(() => sleepSync(undefined)).toThrow();
+ expect(() => sleepSync(null)).toThrow();
+});
+
+it("sleepSync with negative number throws", async () => {
+ expect(() => sleepSync(-10)).toThrow();
+});
+
+it("can map with sleepSync", async () => {
+ [1, 2, 3].map(sleepSync);
+});
diff --git a/test/bun.js/sqlite.test.js b/test/bun.js/sqlite.test.js
index 3120283f4..408fa5a26 100644
--- a/test/bun.js/sqlite.test.js
+++ b/test/bun.js/sqlite.test.js
@@ -504,3 +504,26 @@ it("latin1 supplement chars", () => {
},
]);
});
+
+describe("Database.run", () => {
+ it("should not throw error `not an error` when provided query containing only whitespace", () => {
+ const db = Database.open(":memory:");
+ db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)");
+
+ expect(db[Symbol.for("Bun.Database.cache.count")]).toBe(0);
+
+ var q = db.query("SELECT * FROM test WHERE name = ?");
+ expect(q.get("Hello") === null).toBe(true);
+
+ db.exec('INSERT INTO test (name) VALUES ("Hello")');
+ db.exec('INSERT INTO test (name) VALUES ("World")');
+
+ try {
+ db.run(" ");
+ expect(true).toBeFalsy();
+ } catch (e) {
+ expect(e.message).not.toBe("not an error");
+ expect(e.message).toBe("Query contained no valid SQL statement; likely empty query.");
+ }
+ });
+});
diff --git a/test/snippets/code-simplification-neql-define.js b/test/snippets/code-simplification-neql-define.js
index c7676dc9b..bd7ab9207 100644
--- a/test/snippets/code-simplification-neql-define.js
+++ b/test/snippets/code-simplification-neql-define.js
@@ -2,7 +2,7 @@ var testFailed = false;
const invariant = () => {
testFailed = true;
};
-var $$m = (arg) => {
+var $$m = arg => {
var module = { exports: {} },
exports = module.exports;
return arg(module, exports);
@@ -12,31 +12,19 @@ var size = 100,
export var $f332019d = $$m(
{
- "relay-runtime/lib/network/RelayQueryResponseCache.js": (
- module,
- exports,
- ) => {
+ "relay-runtime/lib/network/RelayQueryResponseCache.js": (module, exports) => {
var RelayQueryResponseCache = function () {
var foo = function RelayQueryResponseCache(_ref) {
var size = _ref.size,
ttl = _ref.ttl;
!(size > 0)
? process.env.NODE_ENV !== "production"
- ? invariant(
- false,
- "RelayQueryResponseCache: Expected the max cache size to be > 0, got " +
- "`%s`.",
- size,
- )
+ ? invariant(false, "RelayQueryResponseCache: Expected the max cache size to be > 0, got " + "`%s`.", size)
: invariant(false)
: void 0;
!(ttl > 0)
? process.env.NODE_ENV !== "production"
- ? invariant(
- false,
- "RelayQueryResponseCache: Expected the max ttl to be > 0, got `%s`.",
- ttl,
- )
+ ? invariant(false, "RelayQueryResponseCache: Expected the max ttl to be > 0, got `%s`.", ttl)
: invariant(false)
: void 0;
};
diff --git a/test/snippets/export.js b/test/snippets/export.js
index 2a757269f..bf334f025 100644
--- a/test/snippets/export.js
+++ b/test/snippets/export.js
@@ -21,9 +21,6 @@ export function test() {
if (where.default !== "hi") {
throw new Error(`_auth import is incorrect.`);
}
- console.assert(
- powerLevel.description === "9001",
- "Symbol is not exported correctly",
- );
+ console.assert(powerLevel.description === "9001", "Symbol is not exported correctly");
return testDone(import.meta.url);
}
diff --git a/test/snippets/jsx-entities.jsx b/test/snippets/jsx-entities.jsx
index ac5d32225..7123fd674 100644
--- a/test/snippets/jsx-entities.jsx
+++ b/test/snippets/jsx-entities.jsx
@@ -926,10 +926,7 @@ export function test() {
key = txt.value;
}
- console.assert(
- elements[rawKey] === key.codePointAt(0),
- `${key} is not ${elements[rawKey]}`,
- );
+ console.assert(elements[rawKey] === key.codePointAt(0), `${key} is not ${elements[rawKey]}`);
}
return testDone(import.meta.url);
diff --git a/test/snippets/latin1-chars-in-regexp.js b/test/snippets/latin1-chars-in-regexp.js
index 1a533b1e1..0ba85d100 100644
--- a/test/snippets/latin1-chars-in-regexp.js
+++ b/test/snippets/latin1-chars-in-regexp.js
@@ -10,40 +10,24 @@
export var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
export var re_btou = new RegExp(
- [
- "[\xC0-\xDF][\x80-\xBF]",
- "[\xE0-\xEF][\x80-\xBF]{2}",
- "[\xF0-\xF7][\x80-\xBF]{3}",
- ].join("|"),
+ ["[\xC0-\xDF][\x80-\xBF]", "[\xE0-\xEF][\x80-\xBF]{2}", "[\xF0-\xF7][\x80-\xBF]{3}"].join("|"),
"g",
);
const encoder = new TextEncoder();
-const realLines = [
- "[\xC0-\xDF][\x80-\xBF]",
- "[\xE0-\xEF][\x80-\xBF]{2}",
- "[\xF0-\xF7][\x80-\xBF]{3}",
-];
-const real = realLines.map((input) => Array.from(encoder.encode(input)));
+const realLines = ["[\xC0-\xDF][\x80-\xBF]", "[\xE0-\xEF][\x80-\xBF]{2}", "[\xF0-\xF7][\x80-\xBF]{3}"];
+const real = realLines.map(input => Array.from(encoder.encode(input)));
const expected = [
[91, 195, 128, 45, 195, 159, 93, 91, 194, 128, 45, 194, 191, 93],
- [
- 91, 195, 160, 45, 195, 175, 93, 91, 194, 128, 45, 194, 191, 93, 123, 50,
- 125,
- ],
- [
- 91, 195, 176, 45, 195, 183, 93, 91, 194, 128, 45, 194, 191, 93, 123, 51,
- 125,
- ],
+ [91, 195, 160, 45, 195, 175, 93, 91, 194, 128, 45, 194, 191, 93, 123, 50, 125],
+ [91, 195, 176, 45, 195, 183, 93, 91, 194, 128, 45, 194, 191, 93, 123, 51, 125],
];
const newlinePreserved = `\n`;
export function test() {
- if (
- !real.every((point, i) => point.every((val, j) => val === expected[i][j]))
- ) {
+ if (!real.every((point, i) => point.every((val, j) => val === expected[i][j]))) {
throw new Error(
`test failed
${JSON.stringify({ expected, real }, null, 2)}`,
@@ -55,11 +39,7 @@ ${JSON.stringify({ expected, real }, null, 2)}`,
}
const decoder = new TextDecoder("utf8");
- if (
- !realLines.every(
- (line, i) => decoder.decode(Uint8Array.from(expected[i])) === line,
- )
- ) {
+ if (!realLines.every((line, i) => decoder.decode(Uint8Array.from(expected[i])) === line)) {
throw new Error(
`test failed. Lines did not match.
${JSON.stringify({ expected, real }, null, 2)}`,
diff --git a/test/snippets/optional-chain-with-function.js b/test/snippets/optional-chain-with-function.js
index 82ad51d46..841c8a584 100644
--- a/test/snippets/optional-chain-with-function.js
+++ b/test/snippets/optional-chain-with-function.js
@@ -3,10 +3,10 @@ export function test() {
const multipleSecondaryValues = undefined;
const ratings = ["123"];
- var bar = multipleSecondaryValues?.map((value) => false);
- bar = bar?.multipleSecondaryValues?.map((value) => false);
- bar = bar?.bar?.multipleSecondaryValues?.map((value) => false);
- bar = {}?.bar?.multipleSecondaryValues?.map((value) => false);
+ var bar = multipleSecondaryValues?.map(value => false);
+ bar = bar?.multipleSecondaryValues?.map(value => false);
+ bar = bar?.bar?.multipleSecondaryValues?.map(value => false);
+ bar = {}?.bar?.multipleSecondaryValues?.map(value => false);
} catch (e) {
throw e;
}
diff --git a/test/snippets/package.json b/test/snippets/package.json
index 0c05b97be..478234d5c 100644
--- a/test/snippets/package.json
+++ b/test/snippets/package.json
@@ -10,5 +10,6 @@
"react-dom": "^17.0.2",
"redux": "^4.1.1",
"styled-components": "^5.3.1"
- }
+ },
+ "prettier": "../../.prettierrc.cjs"
}
diff --git a/test/snippets/react-context-value-func.tsx b/test/snippets/react-context-value-func.tsx
index e7ced1292..800ad428d 100644
--- a/test/snippets/react-context-value-func.tsx
+++ b/test/snippets/react-context-value-func.tsx
@@ -12,7 +12,7 @@ const ContextProvider = ({ children }) => {
const ContextValue = ({}) => (
<Context.Consumer>
- {(foo) => {
+ {foo => {
if (foo) {
return <div>Worked!</div>;
}
diff --git a/test/snippets/simple-lit-example.ts b/test/snippets/simple-lit-example.ts
index 3c53f03ab..1b10b61db 100644
--- a/test/snippets/simple-lit-example.ts
+++ b/test/snippets/simple-lit-example.ts
@@ -3,7 +3,7 @@ import { LitElement, html, css } from "lit";
import { customElement, property, eventOptions } from "lit/decorators.js";
var loadedResolve;
-var loadedPromise = new Promise((resolve) => {
+var loadedPromise = new Promise(resolve => {
loadedResolve = resolve;
});
@@ -35,11 +35,7 @@ export class MyElement extends LitElement {
@property() planet = "Earth";
render() {
- return html`
- <span @click=${this.togglePlanet} class="planet" id="planet-id"
- >${this.planet}</span
- >
- `;
+ return html` <span @click=${this.togglePlanet} class="planet" id="planet-id">${this.planet}</span> `;
}
@eventOptions({ once: true })
diff --git a/test/snippets/spread_with_key.tsx b/test/snippets/spread_with_key.tsx
index d9f842d27..2dc0c7072 100644
--- a/test/snippets/spread_with_key.tsx
+++ b/test/snippets/spread_with_key.tsx
@@ -4,12 +4,7 @@ import React from "react";
export function SpreadWithTheKey({ className }: Props) {
const rest = {};
return (
- <div
- className={className}
- key="spread-with-the-key"
- {...rest}
- onClick={() => console.log("click")}
- >
+ <div className={className} key="spread-with-the-key" {...rest} onClick={() => console.log("click")}>
Rendered component containing warning
</div>
);
diff --git a/test/snippets/string-escapes.js b/test/snippets/string-escapes.js
index 436140939..5fbc8da6c 100644
--- a/test/snippets/string-escapes.js
+++ b/test/snippets/string-escapes.js
@@ -30,31 +30,23 @@ const encoder = new TextEncoder();
const encodedObj = encoder.encode(JSON.stringify(obj));
// ------------------------------------------------------------
const correctEncodedObj = [
- 123, 34, 92, 114, 92, 110, 34, 58, 34, 92, 114, 92, 110, 34, 44, 34, 92, 110,
- 34, 58, 34, 92, 110, 34, 44, 34, 92, 116, 34, 58, 34, 92, 116, 34, 44, 34, 92,
- 102, 34, 58, 34, 92, 102, 34, 44, 34, 92, 117, 48, 48, 48, 98, 34, 58, 34, 92,
- 117, 48, 48, 48, 98, 34, 44, 34, 226, 128, 168, 34, 58, 34, 226, 128, 168, 34,
- 44, 34, 226, 128, 169, 34, 58, 34, 226, 128, 169, 34, 44, 34, 92, 117, 48, 48,
- 48, 48, 34, 58, 34, 92, 117, 48, 48, 48, 48, 194, 160, 110, 117, 108, 108, 32,
- 98, 121, 116, 101, 34, 44, 34, 240, 159, 152, 138, 34, 58, 34, 240, 159, 152,
- 138, 34, 44, 34, 240, 159, 152, 131, 34, 58, 34, 240, 159, 152, 131, 34, 44,
- 34, 240, 159, 149, 181, 240, 159, 143, 189, 226, 128, 141, 226, 153, 130, 239,
- 184, 143, 34, 58, 34, 240, 159, 149, 181, 240, 159, 143, 189, 226, 128, 141,
- 226, 153, 130, 239, 184, 143, 34, 44, 34, 227, 139, 161, 34, 58, 34, 227, 139,
- 161, 34, 44, 34, 226, 152, 186, 34, 58, 34, 226, 152, 186, 34, 44, 34, 227,
- 130, 183, 34, 58, 34, 227, 130, 183, 34, 44, 34, 240, 159, 145, 139, 34, 58,
- 34, 240, 159, 145, 139, 34, 44, 34, 102, 34, 58, 34, 226, 130, 135, 34, 44,
- 34, 226, 152, 185, 34, 58, 34, 226, 152, 185, 34, 44, 34, 226, 152, 187, 34,
- 58, 34, 226, 152, 187, 34, 44, 34, 99, 104, 105, 108, 100, 114, 101, 110, 34,
- 58, 49, 50, 51, 125,
+ 123, 34, 92, 114, 92, 110, 34, 58, 34, 92, 114, 92, 110, 34, 44, 34, 92, 110, 34, 58, 34, 92, 110, 34, 44, 34, 92,
+ 116, 34, 58, 34, 92, 116, 34, 44, 34, 92, 102, 34, 58, 34, 92, 102, 34, 44, 34, 92, 117, 48, 48, 48, 98, 34, 58, 34,
+ 92, 117, 48, 48, 48, 98, 34, 44, 34, 226, 128, 168, 34, 58, 34, 226, 128, 168, 34, 44, 34, 226, 128, 169, 34, 58, 34,
+ 226, 128, 169, 34, 44, 34, 92, 117, 48, 48, 48, 48, 34, 58, 34, 92, 117, 48, 48, 48, 48, 194, 160, 110, 117, 108, 108,
+ 32, 98, 121, 116, 101, 34, 44, 34, 240, 159, 152, 138, 34, 58, 34, 240, 159, 152, 138, 34, 44, 34, 240, 159, 152, 131,
+ 34, 58, 34, 240, 159, 152, 131, 34, 44, 34, 240, 159, 149, 181, 240, 159, 143, 189, 226, 128, 141, 226, 153, 130, 239,
+ 184, 143, 34, 58, 34, 240, 159, 149, 181, 240, 159, 143, 189, 226, 128, 141, 226, 153, 130, 239, 184, 143, 34, 44, 34,
+ 227, 139, 161, 34, 58, 34, 227, 139, 161, 34, 44, 34, 226, 152, 186, 34, 58, 34, 226, 152, 186, 34, 44, 34, 227, 130,
+ 183, 34, 58, 34, 227, 130, 183, 34, 44, 34, 240, 159, 145, 139, 34, 58, 34, 240, 159, 145, 139, 34, 44, 34, 102, 34,
+ 58, 34, 226, 130, 135, 34, 44, 34, 226, 152, 185, 34, 58, 34, 226, 152, 185, 34, 44, 34, 226, 152, 187, 34, 58, 34,
+ 226, 152, 187, 34, 44, 34, 99, 104, 105, 108, 100, 114, 101, 110, 34, 58, 49, 50, 51, 125,
];
export const jsxVariants = (
<>
- "\r\n": "\r\n", "\n": "\n", "\t": "\t", "\f": "\f", "\v": "\v", "\u2028":
- "\u2028", "\u2029": "\u2029", "😊": "😊", "😃": "😃", "🕵🏽‍♂️": "🕵🏽‍♂️", "㋡":
- "㋡", "☺": "☺", シ: "シ", "👋": "👋", f: f, "☹": "☹", "☻": "☻", children:
- 123,
+ "\r\n": "\r\n", "\n": "\n", "\t": "\t", "\f": "\f", "\v": "\v", "\u2028": "\u2028", "\u2029": "\u2029", "😊": "😊",
+ "😃": "😃", "🕵🏽‍♂️": "🕵🏽‍♂️", "㋡": "㋡", "☺": "☺", シ: "シ", "👋": "👋", f: f, "☹": "☹", "☻": "☻", children: 123,
<div data="\r\n" />
<div data="\n" />
<div data="\t" />
diff --git a/test/snippets/styledcomponents-output.js b/test/snippets/styledcomponents-output.js
index fca6e8407..91c871770 100644
--- a/test/snippets/styledcomponents-output.js
+++ b/test/snippets/styledcomponents-output.js
@@ -3,8 +3,7 @@ import React from "react";
import ReactDOM from "react-dom";
const ErrorScreenRoot = styled.div`
- font-family: "Muli", -apple-system, BlinkMacSystemFont, Helvetica, Arial,
- sans-serif;
+ font-family: "Muli", -apple-system, BlinkMacSystemFont, Helvetica, Arial, sans-serif;
position: fixed;
top: 0;
left: 0;
@@ -18,8 +17,7 @@ const ErrorScreenRoot = styled.div`
text-align: center;
background-color: #0b2988;
color: #fff;
- font-family: "Muli", -apple-system, BlinkMacSystemFont, Helvetica, Arial,
- sans-serif;
+ font-family: "Muli", -apple-system, BlinkMacSystemFont, Helvetica, Arial, sans-serif;
line-height: 1.5em;
& > p {
@@ -35,23 +33,15 @@ export function test() {
if (typeof window !== "undefined") {
const reactEl = document.createElement("div");
document.body.appendChild(reactEl);
- ReactDOM.render(
- <ErrorScreenRoot id="error-el">
- The react child should have this text
- </ErrorScreenRoot>,
- reactEl,
- );
+ ReactDOM.render(<ErrorScreenRoot id="error-el">The react child should have this text</ErrorScreenRoot>, reactEl);
const style = document.querySelector("style[data-styled]");
console.assert(style, "style tag should exist");
console.assert(
- style.textContent.split("").every((a) => a.codePointAt(0) < 128),
+ style.textContent.split("").every(a => a.codePointAt(0) < 128),
"style tag should not contain invalid unicode codepoints",
);
- console.assert(
- document.querySelector("#error-el").textContent ===
- "The react child should have this text",
- );
+ console.assert(document.querySelector("#error-el").textContent === "The react child should have this text");
ReactDOM.unmountComponentAtNode(reactEl);
reactEl.remove();
diff --git a/test/snippets/template-literal.js b/test/snippets/template-literal.js
index a5749a555..8d8f64917 100644
--- a/test/snippets/template-literal.js
+++ b/test/snippets/template-literal.js
@@ -1,4 +1,4 @@
-const css = (templ) => templ.toString();
+const css = templ => templ.toString();
const fooNoBracesUTF8 = css`
before
@@ -25,8 +25,7 @@ const fooUTF16 = css`
`;
-const templateLiteralWhichDefinesAFunction = ((...args) =>
- args[args.length - 1]().toString())`
+const templateLiteralWhichDefinesAFunction = ((...args) => args[args.length - 1]().toString())`
before
🙃 ${() => true}
after
@@ -35,17 +34,11 @@ const templateLiteralWhichDefinesAFunction = ((...args) =>
export function test() {
for (let foo of [fooNoBracesUT16, fooNoBracesUTF8, fooUTF16, fooUTF8]) {
- console.assert(
- foo.includes("before"),
- `Expected ${foo} to include "before"`,
- );
+ console.assert(foo.includes("before"), `Expected ${foo} to include "before"`);
console.assert(foo.includes("after"), `Expected ${foo} to include "after"`);
}
- console.assert(
- templateLiteralWhichDefinesAFunction.includes("true"),
- "Expected fooFunction to include 'true'",
- );
+ console.assert(templateLiteralWhichDefinesAFunction.includes("true"), "Expected fooFunction to include 'true'");
return testDone(import.meta.url);
}
diff --git a/test/snippets/type-only-imports.ts b/test/snippets/type-only-imports.ts
index c43fcf278..38d02c743 100644
--- a/test/snippets/type-only-imports.ts
+++ b/test/snippets/type-only-imports.ts
@@ -3,8 +3,7 @@ import type Bacon from "tree";
import type { SilentSymbolCollisionsAreOkayInTypeScript } from "./app";
export const baconator: Bacon = true;
-export const SilentSymbolCollisionsAreOkayInTypeScript: SilentSymbolCollisionsAreOkayInTypeScript =
- true;
+export const SilentSymbolCollisionsAreOkayInTypeScript: SilentSymbolCollisionsAreOkayInTypeScript = true;
export function test() {
console.assert(SilentSymbolCollisionsAreOkayInTypeScript);