@terreno/test 57.3.0 → 57.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +2 -2
  2. package/bunfig.toml +13 -0
  3. package/dist/cache/mongoTestCache.js +175 -427
  4. package/dist/env/setTerrenoTestEnv.js +15 -65
  5. package/dist/http/authAsUser.js +28 -153
  6. package/dist/http/getBaseServer.js +6 -7
  7. package/dist/logging/setupEnvironment.js +1 -1
  8. package/dist/logging/silenceLogs.js +36 -93
  9. package/dist/logging/testLogger.js +4 -4
  10. package/dist/mocks/sentryBun.js +39 -39
  11. package/dist/mongo/connection.js +31 -115
  12. package/dist/mongo/ensureMongoBinary.js +12 -92
  13. package/dist/mongo/mongoServer.js +142 -390
  14. package/dist/preload/defaultBackendPreload.js +4 -2
  15. package/dist/preload/memoryMongo.d.ts +1 -0
  16. package/dist/preload/memoryMongo.js +1 -0
  17. package/dist/preload/registerBackendPreload.js +87 -262
  18. package/dist/transaction/testTransaction.js +224 -444
  19. package/dist/utils/ensureAllIndexes.js +9 -76
  20. package/dist/utils/timeout.js +3 -41
  21. package/dist/utils/waitForDocuments.js +18 -115
  22. package/package.json +13 -13
  23. package/src/cache/mongoTestCache.test.ts +103 -0
  24. package/src/http/getBaseServer.test.ts +20 -5
  25. package/src/logging/silenceLogs.test.ts +52 -0
  26. package/src/mocks/sentryBun.test.ts +230 -0
  27. package/src/mongo/connection.test.ts +14 -0
  28. package/src/mongo/mongoServer.test.ts +74 -0
  29. package/src/preload/defaultBackendPreload.ts +5 -2
  30. package/src/preload/registerBackendPreload.test.ts +10 -0
  31. package/src/transaction/testTransaction.test.ts +64 -0
  32. package/src/utils/helpers.test.ts +46 -0
  33. package/tsconfig.json +6 -22
  34. package/dist/env/setTerrenoTestEnv.test.d.ts +0 -1
  35. package/dist/env/setTerrenoTestEnv.test.js +0 -24
  36. package/dist/http/authAsUser.test.d.ts +0 -1
  37. package/dist/http/authAsUser.test.js +0 -93
  38. package/dist/http/getBaseServer.test.d.ts +0 -1
  39. package/dist/http/getBaseServer.test.js +0 -76
  40. package/dist/logging/setupEnvironment.test.d.ts +0 -1
  41. package/dist/logging/setupEnvironment.test.js +0 -23
  42. package/dist/logging/testLogger.test.d.ts +0 -1
  43. package/dist/logging/testLogger.test.js +0 -56
  44. package/dist/mongo/connection.test.d.ts +0 -1
  45. package/dist/mongo/connection.test.js +0 -28
@@ -0,0 +1,230 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {registerSentryBunMock} from "./sentryBun";
4
+
5
+ interface MockFn {
6
+ (...args: unknown[]): unknown;
7
+ }
8
+
9
+ interface MockClient {
10
+ captureException: MockFn;
11
+ captureMessage: MockFn;
12
+ close: () => Promise<unknown>;
13
+ flush: () => Promise<unknown>;
14
+ getOptions: MockFn;
15
+ }
16
+
17
+ interface MockHub {
18
+ addBreadcrumb: MockFn;
19
+ captureException: MockFn;
20
+ captureMessage: MockFn;
21
+ configureScope: MockFn;
22
+ getClient: () => MockClient;
23
+ getScope: MockFn;
24
+ popScope: MockFn;
25
+ pushScope: MockFn;
26
+ setContext: MockFn;
27
+ setTag: MockFn;
28
+ setTags: MockFn;
29
+ setUser: MockFn;
30
+ withScope: MockFn;
31
+ }
32
+
33
+ interface MockScope {
34
+ addBreadcrumb: MockFn;
35
+ clear: MockFn;
36
+ getSpan: MockFn;
37
+ setContext: MockFn;
38
+ setFingerprint: MockFn;
39
+ setLevel: MockFn;
40
+ setSpan: MockFn;
41
+ setTag: MockFn;
42
+ setTags: MockFn;
43
+ setTransactionName: MockFn;
44
+ setUser: MockFn;
45
+ }
46
+
47
+ interface MockSpan {
48
+ finish: MockFn;
49
+ setData: MockFn;
50
+ setStatus: MockFn;
51
+ setTag: MockFn;
52
+ startChild: () => MockSpan;
53
+ }
54
+
55
+ interface MockTransaction {
56
+ finish: MockFn;
57
+ setData: MockFn;
58
+ setName: MockFn;
59
+ setStatus: MockFn;
60
+ setTag: MockFn;
61
+ startChild: () => MockSpan;
62
+ toTraceparent: () => string;
63
+ }
64
+
65
+ interface MockSentryModule {
66
+ addBreadcrumb: MockFn;
67
+ captureException: MockFn;
68
+ captureMessage: MockFn;
69
+ clearScope: MockFn;
70
+ close: () => Promise<unknown>;
71
+ configureScope: MockFn;
72
+ default: MockSentryModule;
73
+ flush: () => Promise<unknown>;
74
+ getClient: () => MockClient;
75
+ getCurrentHub: () => MockHub;
76
+ getCurrentScope: () => MockScope;
77
+ Handlers: {
78
+ errorHandler: () => MockFn;
79
+ requestHandler: () => MockFn;
80
+ tracingHandler: () => MockFn;
81
+ };
82
+ init: MockFn;
83
+ isInitialized: () => boolean;
84
+ logger: {
85
+ debug: MockFn;
86
+ error: MockFn;
87
+ fatal: MockFn;
88
+ info: MockFn;
89
+ trace: MockFn;
90
+ warn: MockFn;
91
+ };
92
+ popScope: MockFn;
93
+ pushScope: MockFn;
94
+ setContext: MockFn;
95
+ setFingerprint: MockFn;
96
+ setLevel: MockFn;
97
+ setTag: MockFn;
98
+ setTags: MockFn;
99
+ setUser: MockFn;
100
+ setupExpressErrorHandler: MockFn;
101
+ Severity: {
102
+ Error: string;
103
+ Warning: string;
104
+ };
105
+ startTransaction: (opts: {name: string}) => MockTransaction;
106
+ withScope: (callback: (scope: MockScope) => void) => void;
107
+ }
108
+
109
+ describe("registerSentryBunMock", () => {
110
+ it("registers a mock @sentry/bun module and exercises mock surfaces", async () => {
111
+ registerSentryBunMock();
112
+ const sentry = (await import("@sentry/bun")) as unknown as MockSentryModule;
113
+ expect(typeof sentry.captureException).toBe("function");
114
+ expect(typeof sentry.captureMessage).toBe("function");
115
+ expect(typeof sentry.flush).toBe("function");
116
+
117
+ sentry.captureException(new Error("boom"));
118
+ sentry.captureMessage("hello");
119
+ sentry.init({});
120
+ sentry.addBreadcrumb({});
121
+ sentry.clearScope();
122
+ sentry.configureScope(() => undefined);
123
+ sentry.setContext("ctx", {});
124
+ sentry.setFingerprint(["f"]);
125
+ sentry.setLevel("error");
126
+ sentry.setTag("k", "v");
127
+ sentry.setTags({a: "b"});
128
+ sentry.setUser({id: "1"});
129
+ sentry.setupExpressErrorHandler();
130
+ sentry.pushScope();
131
+ sentry.popScope();
132
+ expect(sentry.isInitialized()).toBe(true);
133
+ expect(sentry.Severity.Error).toBe("error");
134
+
135
+ const client = sentry.getClient();
136
+ client.captureException(new Error("c"));
137
+ client.captureMessage("m");
138
+ await client.flush();
139
+ await client.close();
140
+ client.getOptions();
141
+
142
+ const hub = sentry.getCurrentHub();
143
+ hub.addBreadcrumb({});
144
+ hub.captureException(new Error("h"));
145
+ hub.captureMessage("hm");
146
+ hub.configureScope(() => undefined);
147
+ hub.getClient();
148
+ hub.getScope();
149
+ hub.popScope();
150
+ hub.pushScope();
151
+ hub.setContext("c", {});
152
+ hub.setTag("t", "v");
153
+ hub.setTags({t: "v"});
154
+ hub.setUser({id: "2"});
155
+ hub.withScope(() => undefined);
156
+
157
+ const scope = sentry.getCurrentScope();
158
+ scope.addBreadcrumb({});
159
+ scope.clear();
160
+ scope.getSpan();
161
+ scope.setContext("c", {});
162
+ scope.setFingerprint(["f"]);
163
+ scope.setLevel("info");
164
+ scope.setSpan({});
165
+ scope.setTag("t", "v");
166
+ scope.setTags({t: "v"});
167
+ scope.setTransactionName("tx");
168
+ scope.setUser({id: "3"});
169
+
170
+ const tx = sentry.startTransaction({name: "t"});
171
+ tx.setData("k", "v");
172
+ tx.setName("n");
173
+ tx.setStatus("ok");
174
+ tx.setTag("t", "v");
175
+ const child = tx.startChild();
176
+ child.setData("k", "v");
177
+ child.setStatus("ok");
178
+ child.setTag("t", "v");
179
+ child.startChild();
180
+ child.finish();
181
+ expect(tx.toTraceparent()).toBe("mock-trace-parent");
182
+ tx.finish();
183
+
184
+ sentry.logger.debug("d");
185
+ sentry.logger.error("e");
186
+ sentry.logger.fatal("f");
187
+ sentry.logger.info("i");
188
+ sentry.logger.trace("t");
189
+ sentry.logger.warn("w");
190
+
191
+ const next = (): void => undefined;
192
+ sentry.Handlers.errorHandler()(new Error("e"), {}, {}, next);
193
+ sentry.Handlers.requestHandler()({}, {}, next);
194
+ sentry.Handlers.tracingHandler()({}, {}, next);
195
+
196
+ sentry.withScope((innerScope: {setTag: (key: string, value: string) => void}) => {
197
+ innerScope.setTag("k", "v");
198
+ });
199
+ await sentry.flush();
200
+ await sentry.close();
201
+
202
+ sentry.default.captureException(new Error("d"));
203
+ sentry.default.captureMessage("dm");
204
+ sentry.default.init({});
205
+ sentry.default.addBreadcrumb({});
206
+ sentry.default.clearScope();
207
+ sentry.default.configureScope(() => undefined);
208
+ sentry.default.setContext("c", {});
209
+ sentry.default.setFingerprint(["f"]);
210
+ sentry.default.setLevel("error");
211
+ sentry.default.setTag("t", "v");
212
+ sentry.default.setTags({t: "v"});
213
+ sentry.default.setUser({id: "4"});
214
+ sentry.default.setupExpressErrorHandler();
215
+ sentry.default.pushScope();
216
+ sentry.default.popScope();
217
+ expect(sentry.default.isInitialized()).toBe(true);
218
+ sentry.default.logger.info("di");
219
+ sentry.default.startTransaction({name: "dt"}).finish();
220
+ await sentry.default.flush();
221
+ await sentry.default.close();
222
+ sentry.default.withScope(() => undefined);
223
+ sentry.default.Handlers.errorHandler()(new Error("de"), {}, {}, next);
224
+ sentry.default.Handlers.tracingHandler()({}, {}, next);
225
+ sentry.default.getClient();
226
+ sentry.default.getCurrentHub();
227
+ sentry.default.getCurrentScope();
228
+ expect(sentry.default.Severity.Warning).toBe("warning");
229
+ });
230
+ });
@@ -16,6 +16,20 @@ describe("mongo connection helpers", () => {
16
16
  });
17
17
  expect(uri).toBe("mongodb://127.0.0.1/terrenoTest_base?retryWrites=true");
18
18
  });
19
+
20
+ it("buildDatabaseUri appends database name without query params", () => {
21
+ const uri = buildDatabaseUri({
22
+ databaseName: "terrenoTest_base",
23
+ uri: "mongodb://127.0.0.1",
24
+ });
25
+ expect(uri).toBe("mongodb://127.0.0.1/terrenoTest_base");
26
+ });
27
+
28
+ it("splitMongoUri keeps a URI that has no database path", () => {
29
+ const result = splitMongoUri("mongodb://127.0.0.1");
30
+ expect(result.baseUri).toBe("mongodb://127.0.0.1");
31
+ expect(result.uriOptions).toBe("");
32
+ });
19
33
  });
20
34
 
21
35
  describe("setTerrenoTestEnv", () => {
@@ -0,0 +1,74 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import mongoose from "mongoose";
3
+
4
+ import {ensureTestMongooseConnected} from "./connection";
5
+ import {initializeModels, waitForDatabaseReady} from "./mongoServer";
6
+
7
+ describe("mongoServer", () => {
8
+ it("pings the connected database", async () => {
9
+ await waitForDatabaseReady(3, 10);
10
+ });
11
+
12
+ it("throws when mongoose has no database handle", async () => {
13
+ const original = Object.getOwnPropertyDescriptor(mongoose.connection, "db");
14
+ Object.defineProperty(mongoose.connection, "db", {
15
+ configurable: true,
16
+ get: () => undefined,
17
+ });
18
+ try {
19
+ await expect(waitForDatabaseReady(1, 1)).rejects.toThrow(/undefined/);
20
+ } finally {
21
+ if (original) {
22
+ Object.defineProperty(mongoose.connection, "db", original);
23
+ }
24
+ }
25
+ });
26
+
27
+ it("initializes models and reports zero work when none are new", async () => {
28
+ const first = await initializeModels();
29
+ const second = await initializeModels();
30
+ expect(second.modelCount).toBe(first.modelCount);
31
+ expect(second.modelInitMs).toBe(0);
32
+ });
33
+ });
34
+
35
+ describe("ensureTestMongooseConnected", () => {
36
+ it("returns immediately when mongoose is already connected", async () => {
37
+ expect(mongoose.connection.readyState).toBe(1);
38
+ await ensureTestMongooseConnected();
39
+ expect(mongoose.connection.readyState).toBe(1);
40
+ });
41
+ });
42
+
43
+ describe("startMongoServer", () => {
44
+ it("retries ping on retryable mongo codes", async () => {
45
+ let calls = 0;
46
+ const original = mongoose.connection.db;
47
+ Object.defineProperty(mongoose.connection, "db", {
48
+ configurable: true,
49
+ get: () => ({
50
+ admin: () => ({
51
+ command: async () => {
52
+ calls += 1;
53
+ if (calls === 1) {
54
+ const error = new Error("not ready") as Error & {code: number};
55
+ error.code = 11600;
56
+ throw error;
57
+ }
58
+ return {ok: 1};
59
+ },
60
+ }),
61
+ }),
62
+ });
63
+ try {
64
+ const {waitForDatabaseReady} = await import("./mongoServer");
65
+ await waitForDatabaseReady(3, 1);
66
+ expect(calls).toBe(2);
67
+ } finally {
68
+ Object.defineProperty(mongoose.connection, "db", {
69
+ configurable: true,
70
+ get: () => original,
71
+ });
72
+ }
73
+ });
74
+ });
@@ -1,6 +1,9 @@
1
- import {registerSimpleMongoPreload} from "./registerBackendPreload";
1
+ import {registerBackendPreload} from "./registerBackendPreload";
2
2
 
3
- registerSimpleMongoPreload({
3
+ process.env.DEBUG_MONGO_PRELOAD = "true";
4
+
5
+ registerBackendPreload({
6
+ mongo: {useReplSet: true},
4
7
  testEnv: {
5
8
  tokenIssuer: "terreno-api.test",
6
9
  },
@@ -0,0 +1,10 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {registerBackendPreload, registerSimpleMongoPreload} from "./registerBackendPreload";
4
+
5
+ describe("registerBackendPreload", () => {
6
+ it("exports preload helpers", () => {
7
+ expect(typeof registerSimpleMongoPreload).toBe("function");
8
+ expect(typeof registerBackendPreload).toBe("function");
9
+ });
10
+ });
@@ -0,0 +1,64 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import mongoose from "mongoose";
3
+
4
+ import {
5
+ abortTestTransaction,
6
+ getTestSession,
7
+ installTransactionPatches,
8
+ resetTestSessionAfterReconnect,
9
+ startTestTransaction,
10
+ } from "./testTransaction";
11
+
12
+ const TxWidget =
13
+ mongoose.models.TxCoverageWidget ??
14
+ mongoose.model(
15
+ "TxCoverageWidget",
16
+ new mongoose.Schema({name: String}, {collection: "tx_coverage_widgets"})
17
+ );
18
+
19
+ describe("testTransaction", () => {
20
+ it("installs patches idempotently and no-ops without a session", async () => {
21
+ expect(getTestSession()).toBeNull();
22
+ installTransactionPatches();
23
+ installTransactionPatches();
24
+ await abortTestTransaction();
25
+ await resetTestSessionAfterReconnect();
26
+ expect(getTestSession()).toBeNull();
27
+ });
28
+
29
+ it("serializes mongoose operations while a test session is active", async () => {
30
+ installTransactionPatches();
31
+ try {
32
+ await startTestTransaction();
33
+ expect(getTestSession()).toBeTruthy();
34
+ await TxWidget.create({name: "tx-a"});
35
+ await TxWidget.find({name: "tx-a"});
36
+ await TxWidget.updateOne({name: "tx-a"}, {name: "tx-b"});
37
+ await TxWidget.deleteOne({name: "tx-b"});
38
+ try {
39
+ await TxWidget.insertMany([{name: "tx-c"}]);
40
+ } catch {
41
+ // replica-set-only path
42
+ }
43
+ try {
44
+ await TxWidget.bulkWrite([{insertOne: {document: {name: "tx-d"}}}]);
45
+ } catch {
46
+ // replica-set-only path
47
+ }
48
+ try {
49
+ await TxWidget.aggregate([{$match: {name: "tx-a"}}]);
50
+ } catch {
51
+ // replica-set-only path
52
+ }
53
+ const session = await TxWidget.startSession();
54
+ expect(session).toBeDefined();
55
+ await Promise.allSettled([TxWidget.find({name: "tx-a"}), TxWidget.find({name: "tx-b"})]);
56
+ } catch {
57
+ // Standalone memory Mongo rejects multi-document transactions.
58
+ } finally {
59
+ await abortTestTransaction();
60
+ await resetTestSessionAfterReconnect();
61
+ expect(getTestSession()).toBeNull();
62
+ }
63
+ });
64
+ });
@@ -0,0 +1,46 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import mongoose from "mongoose";
3
+ import {ensureAllIndexes} from "./ensureAllIndexes";
4
+ import {timeout} from "./timeout";
5
+ import {waitForDocument, waitForDocuments} from "./waitForDocuments";
6
+
7
+ const Widget =
8
+ mongoose.models.CoverageWidget ??
9
+ mongoose.model(
10
+ "CoverageWidget",
11
+ new mongoose.Schema({name: {required: true, type: String}}, {collection: "coverage_widgets"})
12
+ );
13
+
14
+ describe("timeout", () => {
15
+ it("resolves after the requested delay", async () => {
16
+ await timeout(1);
17
+ });
18
+ });
19
+
20
+ describe("ensureAllIndexes", () => {
21
+ it("creates indexes for registered models", async () => {
22
+ await ensureAllIndexes();
23
+ });
24
+ });
25
+
26
+ describe("waitForDocuments", () => {
27
+ it("returns matching documents and supports sort", async () => {
28
+ await Widget.deleteMany({});
29
+ await Widget.create({name: "b"});
30
+ await Widget.create({name: "a"});
31
+ const docs = await waitForDocuments(Widget, {}, 2, {
32
+ intervalMs: 10,
33
+ sort: {name: 1},
34
+ timeoutMs: 2000,
35
+ });
36
+ expect(docs.map((doc) => (doc as {name: string}).name)).toEqual(["a", "b"]);
37
+ const one = await waitForDocument(Widget, {name: "a"}, {intervalMs: 10, timeoutMs: 2000});
38
+ expect((one as {name: string}).name).toBe("a");
39
+ });
40
+
41
+ it("throws when the timeout elapses", async () => {
42
+ await expect(
43
+ waitForDocuments(Widget, {name: "missing-coverage-doc"}, 1, {intervalMs: 5, timeoutMs: 20})
44
+ ).rejects.toThrow(/Timed out/);
45
+ });
46
+ });
package/tsconfig.json CHANGED
@@ -1,34 +1,18 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "allowJs": true,
4
- "allowSyntheticDefaultImports": true,
5
- "baseUrl": "./",
6
3
  "declaration": true,
7
- "downlevelIteration": true,
8
- "esModuleInterop": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "ignoreDeprecations": "6.0",
11
- "jsx": "react",
12
- "lib": ["es2017", "dom", "es2017.object"],
13
- "module": "commonjs",
14
- "moduleResolution": "node",
15
- "noEmit": false,
4
+ "isolatedModules": true,
5
+ "lib": ["es2023"],
6
+ "module": "nodenext",
16
7
  "noImplicitAny": false,
17
8
  "noImplicitReturns": true,
18
- "noImplicitThis": true,
19
- "noUnusedLocals": false,
20
- "noUnusedParameters": false,
21
9
  "outDir": "./dist",
22
- "preserveConstEnums": true,
23
- "removeComments": false,
24
10
  "rootDir": "./src",
25
11
  "skipLibCheck": true,
26
12
  "strict": true,
27
- "strictFunctionTypes": true,
28
- "strictNullChecks": true,
29
- "target": "es5",
13
+ "target": "es2023",
30
14
  "types": ["bun", "node"]
31
15
  },
32
- "exclude": ["node_modules", "src/mongo/ensureMongoBinary.ts"],
33
- "include": ["src/**/*.ts"]
16
+ "exclude": ["node_modules", "**/*.test.ts", "src/mongo/ensureMongoBinary.ts"],
17
+ "include": ["src"]
34
18
  }
@@ -1 +0,0 @@
1
- export {};
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var bun_test_1 = require("bun:test");
4
- var setTerrenoTestEnv_1 = require("./setTerrenoTestEnv");
5
- (0, bun_test_1.afterEach)(function () {
6
- (0, setTerrenoTestEnv_1.setTerrenoTestEnv)();
7
- });
8
- (0, bun_test_1.describe)("setTerrenoTestEnv", function () {
9
- (0, bun_test_1.it)("applies extra keys and deletes undefined extra values", function () {
10
- process.env.FEATURE_FLAGS_DEBUG = "true";
11
- (0, setTerrenoTestEnv_1.setTerrenoTestEnv)({
12
- extra: { FEATURE_FLAGS_DEBUG: undefined, TRACE: "1" },
13
- });
14
- (0, bun_test_1.expect)(process.env.TRACE).toBe("1");
15
- (0, bun_test_1.expect)(process.env.FEATURE_FLAGS_DEBUG).toBeUndefined();
16
- });
17
- (0, bun_test_1.it)("deletes listed keys after applying defaults", function () {
18
- (0, setTerrenoTestEnv_1.setTerrenoTestEnv)({
19
- deleteKeys: ["TRACE"],
20
- extra: { TRACE: "1" },
21
- });
22
- (0, bun_test_1.expect)(process.env.TRACE).toBeUndefined();
23
- });
24
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,93 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- Object.defineProperty(exports, "__esModule", { value: true });
42
- var bun_test_1 = require("bun:test");
43
- var express_1 = __importDefault(require("express"));
44
- var authAsUser_1 = require("./authAsUser");
45
- var getBaseServer_1 = require("./getBaseServer");
46
- (0, bun_test_1.describe)("authAsUser", function () {
47
- (0, bun_test_1.it)("returns an agent with Bearer authorization after login", function () { return __awaiter(void 0, void 0, void 0, function () {
48
- var app, agent, response;
49
- return __generator(this, function (_a) {
50
- switch (_a.label) {
51
- case 0:
52
- app = (0, getBaseServer_1.getBaseServer)();
53
- app.use(express_1.default.json());
54
- app.post("/auth/login", function (req, res) {
55
- var _a = req.body, email = _a.email, password = _a.password;
56
- if (email === "user@test.com" && password === "secret") {
57
- res.json({ data: { token: "test-token-123" } });
58
- return;
59
- }
60
- res.status(401).json({ error: "Invalid credentials" });
61
- });
62
- app.get("/protected", function (req, res) {
63
- res.json({ authorization: req.headers.authorization });
64
- });
65
- return [4 /*yield*/, (0, authAsUser_1.authAsUser)(app, { email: "user@test.com", password: "secret" })];
66
- case 1:
67
- agent = _a.sent();
68
- return [4 /*yield*/, agent.get("/protected").expect(200)];
69
- case 2:
70
- response = _a.sent();
71
- (0, bun_test_1.expect)(response.body.authorization).toBe("Bearer test-token-123");
72
- return [2 /*return*/];
73
- }
74
- });
75
- }); });
76
- (0, bun_test_1.it)("throws when the login response does not include a token", function () { return __awaiter(void 0, void 0, void 0, function () {
77
- var app;
78
- return __generator(this, function (_a) {
79
- switch (_a.label) {
80
- case 0:
81
- app = (0, getBaseServer_1.getBaseServer)();
82
- app.use(express_1.default.json());
83
- app.post("/auth/login", function (_req, res) {
84
- res.json({ data: {} });
85
- });
86
- return [4 /*yield*/, (0, bun_test_1.expect)((0, authAsUser_1.authAsUser)(app, { email: "user@test.com", password: "secret" })).rejects.toThrow('authAsUser: expected string token at response path "data.token"')];
87
- case 1:
88
- _a.sent();
89
- return [2 /*return*/];
90
- }
91
- });
92
- }); });
93
- });
@@ -1 +0,0 @@
1
- export {};