Skip to content

Commit

Permalink
refactor: getGitHubUser() test and logic improvements (denoland#577)
Browse files Browse the repository at this point in the history
TSIA
  • Loading branch information
iuioiua authored Sep 12, 2023
1 parent fd453e4 commit ba99111
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
11 changes: 6 additions & 5 deletions plugins/kv_oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
type User,
} from "@/utils/db.ts";
import { isStripeEnabled, stripe } from "@/utils/stripe.ts";
import { createHttpError } from "std/http/http_errors.ts";

const oauth2Client = createGitHubOAuth2Client();

Expand All @@ -38,14 +39,14 @@ interface GitHubUser {
* ```
*/
export async function getGitHubUser(accessToken: string) {
const response = await fetch("https://api.github.com/user", {
const resp = await fetch("https://api.github.com/user", {
headers: { authorization: `Bearer ${accessToken}` },
});
if (!response.ok) {
const { message } = await response.json();
throw new Error(message);
if (!resp.ok) {
const { message } = await resp.json();
throw createHttpError(resp.status, message);
}
return await response.json() as Promise<GitHubUser>;
return await resp.json() as Promise<GitHubUser>;
}

/**
Expand Down
33 changes: 30 additions & 3 deletions plugins/kv_oauth_test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.
import { assertRejects } from "std/assert/assert_rejects.ts";
import { getGitHubUser } from "./kv_oauth.ts";
import {
assertSpyCall,
assertSpyCalls,
returnsNext,
stub,
} from "std/testing/mock.ts";
import { Status } from "$fresh/server.ts";
import { errors } from "std/http/http_errors.ts";
import { assertEquals } from "std/assert/assert_equals.ts";

Deno.test("[plugins] getGitHubUser()", async () => {
const message = crypto.randomUUID();
const resp1Body = { message };
const resp1 = Promise.resolve(
Response.json(resp1Body, { status: Status.BadRequest }),
);
const resp2Body = { login: crypto.randomUUID(), email: crypto.randomUUID() };
const resp2 = Promise.resolve(Response.json(resp2Body));
const fetchStub = stub(globalThis, "fetch", returnsNext([resp1, resp2]));

const accessToken1 = crypto.randomUUID();
const accessToken2 = crypto.randomUUID();
await assertRejects(
async () => await getGitHubUser("access token"),
Error,
"Bad credentials",
async () => await getGitHubUser(accessToken1),
errors.BadRequest,
message,
);
assertEquals(await getGitHubUser(accessToken2), resp2Body);

fetchStub.restore();

assertSpyCall(fetchStub, 0, { returned: resp1 });
assertSpyCall(fetchStub, 1, { returned: resp2 });
assertSpyCalls(fetchStub, 2);
});

0 comments on commit ba99111

Please sign in to comment.