Skip to content

Commit d9ac1f3

Browse files
committed
Add more tests
1 parent f88a6ed commit d9ac1f3

File tree

2 files changed

+54
-7
lines changed

2 files changed

+54
-7
lines changed

src/token.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ function encodeToBase64(data: unknown): string {
2828

2929
// missing crypto global for Node.js 18 https://nodejs.org/api/globals.html#crypto_1
3030
let cryptoPonyfill: Promise<Crypto | typeof webcrypto> | undefined;
31-
function getCrypto() {
31+
function getCrypto(): NonNullable<typeof cryptoPonyfill> {
3232
if (cryptoPonyfill === undefined) {
3333
cryptoPonyfill =
3434
typeof crypto === "undefined"
@@ -143,11 +143,8 @@ function tryDetectEnvironment(): void {
143143

144144
// Node.js prior to v21.1.0 doesn't have the above global
145145
// https://nodejs.org/api/globals.html#navigatoruseragent
146-
if (
147-
Object.hasOwn(globalThis, "process") &&
148-
Object.hasOwn(globalThis.process, "versions") &&
149-
Object.hasOwn(globalThis.process.versions, "node")
150-
) {
146+
const versions = globalThis.process?.versions;
147+
if (versions !== undefined && Object.hasOwn(versions, "node")) {
151148
return;
152149
}
153150

tests/token.test.ts

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import * as assert from "node:assert";
2-
import { afterAll, beforeEach, describe, expect, test } from "vitest";
2+
import {
3+
afterAll,
4+
beforeEach,
5+
describe,
6+
expect,
7+
test,
8+
vi,
9+
type MockInstance,
10+
} from "vitest";
311
import {
412
getClient,
513
decode64,
@@ -21,6 +29,48 @@ afterAll(() => {
2129
return clearAllIndexes(config);
2230
});
2331

32+
test("Should throw error for invalid UID", async () => {
33+
await assert.rejects(
34+
generateTenantToken({
35+
apiKey: "wrong",
36+
apiKeyUid: "stuff",
37+
}),
38+
/^Error: the uid of your key is not a valid UUIDv4$/,
39+
);
40+
});
41+
42+
test("Should throw error for non-server-side environment", async () => {
43+
using _ = (() => {
44+
let userAgentSpy: MockInstance<() => string> | undefined;
45+
if (typeof navigator !== "undefined" && "userAgent" in navigator) {
46+
userAgentSpy = vi
47+
.spyOn(navigator, "userAgent", "get")
48+
.mockImplementation(() => "ProbablySomeBrowserUA");
49+
}
50+
51+
const nodeEvnSpy = vi.spyOn(process, "versions", "get").mockImplementation(
52+
() =>
53+
// @ts-expect-error
54+
undefined,
55+
);
56+
57+
return {
58+
[Symbol.dispose]() {
59+
userAgentSpy?.mockRestore();
60+
nodeEvnSpy.mockRestore();
61+
},
62+
};
63+
})();
64+
65+
await assert.rejects(
66+
generateTenantToken({
67+
apiKey: "wrong",
68+
apiKeyUid: "stuff",
69+
}),
70+
/^Error: failed to detect a server-side environment;/,
71+
);
72+
});
73+
2474
describe.each([{ permission: "Admin" }])(
2575
"Tests on token generation",
2676
({ permission }) => {

0 commit comments

Comments
 (0)