Skip to content

Commit a0adc13

Browse files
add mock for @tsndr/cloudflare-worker-jwt and generateUniqueToken, fix test cases
1 parent d9d2949 commit a0adc13

File tree

6 files changed

+91
-92
lines changed

6 files changed

+91
-92
lines changed

__mocks__/@tsndr/cloudflare-worker-jwt.js

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
1-
"use strict";
2-
import jsonwebtoken from "jsonwebtoken";
3-
4-
const cloudflareWorkerJwt = jest.createMockFromModule("jsonwebtoken");
5-
6-
function sign() {
7-
console.log("ASD");
8-
return "asd";
9-
}
10-
11-
// @ts-ignore
12-
cloudflareWorkerJwt.sign = sign;
13-
14-
module.exports = cloudflareWorkerJwt;
1+
// __mocks__/@tsndr/cloudflare-worker-jwt.js
2+
const mockJwt = {
3+
sign: jest.fn().mockImplementation(() => {
4+
return "SIGNED_JWT";
5+
}),
6+
};
7+
8+
export default mockJwt;

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"scripts": {
66
"start": "wrangler dev",
77
"test": "echo 'running tests 🧪' && jest --coverage && echo '✅ All tests passed'",
8-
"test-watch": "jest --watch",
8+
"test-watch": "jest . --watch",
99
"login": "wrangler login",
1010
"check": "wrangler whoami",
1111
"deploy": "wrangler deploy",

src/controllers/verifyCommand.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { RETRY_COMMAND, VERIFICATION_STRING } from "../constants/responses";
33
import { env } from "../typeDefinitions/default.types";
44
import { discordEphemeralResponse } from "../utils/discordEphemeralResponse";
55
import { generateUniqueToken } from "../utils/generateUniqueToken";
6-
import {sendUserDiscordData} from "../utils/sendUserDiscordData";
6+
import { sendUserDiscordData } from "../utils/sendUserDiscordData";
77

88
export async function verifyCommand(
99
userId: number,
@@ -13,7 +13,8 @@ export async function verifyCommand(
1313
env: env
1414
) {
1515
const token = await generateUniqueToken();
16-
const response = await sendUserDiscordData( token,
16+
const response = await sendUserDiscordData(
17+
token,
1718
userId,
1819
userAvatarHash,
1920
userName,

src/utils/generateUniqueToken.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const crypto = require("crypto");
21
export const generateUniqueToken = async () => {
32
const uuidToken = crypto.randomUUID();
43
const randomNumber = Math.floor(Math.random() * 1000000);
Lines changed: 79 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,105 @@
1-
import * as response from "../../../src/constants/responses";
2-
import JSONResponse from "../../../src/utils/JsonResponse";
3-
import { verifyCommand } from "../../../src/controllers/verifyCommand";
4-
import { guildEnv } from "../../fixtures/fixture";
1+
import {
2+
RETRY_COMMAND,
3+
VERIFICATION_STRING,
4+
} from "../../../src/constants/responses";
55
import config from "../../../config/config";
66

7-
describe("verifyCommand", () => {
8-
test("should return INTERNAL_SERVER_ERROR when response is not ok", async () => {
9-
10-
jest.mock("crypto", () => {
11-
return {
12-
randomUUID: jest.fn(()=>'shreya'),
13-
subtle: { digest: jest.fn(() => "123") },
14-
};
15-
});
7+
const mockDateNow = 1626512345678;
8+
const UNIQUE_TOKEN = "UNIQUE_TOKEN";
9+
const env = {
10+
BOT_PUBLIC_KEY: "BOT_PUBLIC_KEY",
11+
DISCORD_GUILD_ID: "DISCORD_GUILD_ID",
12+
DISCORD_TOKEN: "SIGNED_JWT",
13+
};
1614

15+
describe("verifyCommand", () => {
16+
beforeEach(() => {
17+
jest.mock("@tsndr/cloudflare-worker-jwt");
18+
jest.spyOn(Date, "now").mockReturnValue(mockDateNow);
1719
jest.mock("../../../src/utils/generateUniqueToken", () => ({
18-
generateUniqueToken: () => Promise.resolve("jashdkjahskajhd"),
20+
generateUniqueToken: () => Promise.resolve(UNIQUE_TOKEN),
1921
}));
22+
});
2023

21-
// const mockResponse = response.INTERNAL_SERVER_ERROR;
22-
// jest
23-
// .spyOn(global, "fetch")
24-
// .mockImplementation(() =>
25-
// Promise.resolve(new JSONResponse(mockResponse))
26-
// );
27-
28-
const env = {
29-
BOT_PUBLIC_KEY: "xyz",
30-
DISCORD_GUILD_ID: "123",
31-
DISCORD_TOKEN: "abc",
32-
};
24+
afterEach(() => {
25+
jest.spyOn(Date, "now").mockRestore();
26+
});
3327

28+
test("should return JSON response when response is ok", async () => {
3429
const data = {
35-
token: 1233434,
36-
userId: "sjkhdkjashdksjh",
37-
userAvatarHash: "test user",
38-
userName: "sndbhsbgdj",
39-
env: env,
30+
type: "discord",
31+
token: UNIQUE_TOKEN,
32+
attributes: {
33+
discordId: 1,
34+
userAvatar: "https://cdn.discordapp.com/avatars/1/userAvatarHash.jpg",
35+
userName: "userName",
36+
discriminator: "discriminator",
37+
expiry: mockDateNow + 1000 * 60 * 2,
38+
},
4039
};
4140

41+
jest.spyOn(global, "fetch").mockResolvedValueOnce({
42+
ok: true,
43+
status: 200,
44+
json: jest.fn().mockResolvedValueOnce(data),
45+
} as unknown as Response);
46+
47+
const { verifyCommand } = await import(
48+
"../../../src/controllers/verifyCommand"
49+
);
50+
4251
const result = await verifyCommand(
43-
1233434,
44-
"sjkhdkjashdksjh",
45-
"test user",
46-
"sndbhsbgdj",
52+
1,
53+
"userAvatarHash",
54+
"userName",
55+
"discriminator",
4756
env
4857
);
4958

50-
// expect(result.data.content).toEqual(response.RETRY_COMMAND);
5159
expect(global.fetch).toHaveBeenCalledWith(
52-
`https://api.realdevsquad.com/external-accounts`,
60+
`http://localhost:3000/external-accounts`,
5361
{
5462
method: "POST",
5563
headers: {
5664
"Content-Type": "application/json",
57-
Authorization: `Bot ${guildEnv.DISCORD_TOKEN}`,
65+
Authorization: `Bearer ${env.DISCORD_TOKEN}`,
5866
},
5967
body: JSON.stringify(data),
6068
}
6169
);
62-
});
63-
64-
test("should return JSON response when response is ok", async () => {
65-
const mockResponse = {};
70+
const resultText = await result.text();
71+
const resultData = JSON.parse(resultText);
6672

67-
// jest
68-
// .spyOn(global, "fetch")
69-
// .mockImplementation(() =>
70-
// Promise.resolve(new JSONResponse(mockResponse))
71-
// );
73+
const verificationSiteURL = config(env).VERIFICATION_SITE_URL;
74+
const message =
75+
`${verificationSiteURL}/discord?token=${UNIQUE_TOKEN}\n` +
76+
VERIFICATION_STRING;
7277

73-
const env = {
74-
BOT_PUBLIC_KEY: "xyz",
75-
DISCORD_GUILD_ID: "123",
76-
DISCORD_TOKEN: "abc",
77-
};
78+
expect(resultData.data.content).toEqual(message);
79+
});
7880

81+
test("should return INTERNAL_SERVER_ERROR when response is not ok", async () => {
7982
const data = {
80-
token: 1233434,
81-
userId: "sjkhdkjashdksjh",
82-
userAvatarHash: "test user",
83-
userName: "sndbhsbgdj",
84-
env: env,
83+
type: "discord",
84+
token: UNIQUE_TOKEN,
85+
attributes: {
86+
discordId: 1,
87+
userAvatar: "https://cdn.discordapp.com/avatars/1/userAvatarHash.jpg",
88+
userName: "userName",
89+
discriminator: "discriminator",
90+
expiry: mockDateNow + 1000 * 60 * 2,
91+
},
8592
};
8693

94+
jest.spyOn(global, "fetch").mockResolvedValueOnce({
95+
ok: true,
96+
status: 400, // ERROR STATUS
97+
json: jest.fn().mockResolvedValueOnce(data),
98+
} as unknown as Response);
99+
100+
const { verifyCommand } = await import(
101+
"../../../src/controllers/verifyCommand"
102+
);
87103
const result = await verifyCommand(
88104
1233434,
89105
"sjkhdkjashdksjh",
@@ -92,21 +108,20 @@ describe("verifyCommand", () => {
92108
env
93109
);
94110

95-
const verificationSiteURL = config(env).VERIFICATION_SITE_URL;
96-
const message =
97-
`${verificationSiteURL}/discord?token=${guildEnv.DISCORD_TOKEN}\n` +
98-
response.VERIFICATION_STRING;
99-
100111
expect(global.fetch).toHaveBeenCalledWith(
101-
`https://api.realdevsquad.com/external-accounts`,
112+
`http://localhost:3000/external-accounts`,
102113
{
103114
method: "POST",
104115
headers: {
105116
"Content-Type": "application/json",
106-
Authorization: `Bot ${guildEnv.DISCORD_TOKEN}`,
117+
Authorization: `Bearer ${env.DISCORD_TOKEN}`,
107118
},
108119
body: JSON.stringify(data),
109120
}
110121
);
122+
const resultText = await result.text();
123+
const resultData = JSON.parse(resultText);
124+
125+
expect(resultData.data.content).toEqual(RETRY_COMMAND);
111126
});
112127
});

0 commit comments

Comments
 (0)