Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { LbPersonalBests } from "../../../src/utils/pb";
import { pb } from "../../__testData__/users";
import { createConnection } from "../../__testData__/connections";
import { omit } from "../../../src/utils/misc";
import { LeaderboardEntry } from "@monkeytype/schemas/leaderboards";

describe("LeaderboardsDal", () => {
afterEach(async () => {
Expand Down Expand Up @@ -122,7 +123,7 @@ describe("LeaderboardsDal", () => {
it("should remove consistency from results if null", async () => {
//GIVEN
const stats = pb(100, 90, 2);
//@ts-ignore
//@ts-expect-error ok for testing
stats.consistency = undefined;

await createUser(lbBests(stats));
Expand Down Expand Up @@ -468,11 +469,10 @@ describe("LeaderboardsDal", () => {
function expectedLbEntry(
time: string,
{ rank, user, badgeId, isPremium, friendsRank }: ExpectedLbEntry,
) {
// @ts-expect-error
const lbBest: PersonalBest =
// @ts-expect-error
user.lbPersonalBests?.time[Number.parseInt(time)].english;
): LeaderboardEntry {
const lbBest: PersonalBest = user.lbPersonalBests?.time[
Number.parseInt(time)
]?.["english"] as PersonalBest;

return {
rank,
Expand Down Expand Up @@ -523,7 +523,7 @@ function lbBests(pb15?: PersonalBest, pb60?: PersonalBest): LbPersonalBests {
return result;
}

function premium(expirationDeltaSeconds: number) {
function premium(expirationDeltaSeconds: number): Partial<UserDal.DBUser> {
return {
premium: {
startTimestamp: 0,
Expand Down
6 changes: 3 additions & 3 deletions backend/__tests__/__integration__/dal/preset.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ describe("PresetDal", () => {
}

//WHEN / THEN
await expect(() =>
await expect(async () =>
PresetDal.addPreset(uid, { name: "max", config: {} }),
).rejects.toThrow("Too many presets");
});
Expand Down Expand Up @@ -356,7 +356,7 @@ describe("PresetDal", () => {
describe("removePreset", () => {
it("should fail if preset is unknown", async () => {
const uid = new ObjectId().toHexString();
await expect(() =>
await expect(async () =>
PresetDal.removePreset(uid, new ObjectId().toHexString()),
).rejects.toThrow("Preset not found");
});
Expand Down Expand Up @@ -419,7 +419,7 @@ describe("PresetDal", () => {
).presetId;

//WHEN
await expect(() =>
await expect(async () =>
PresetDal.removePreset(decoyUid, first),
).rejects.toThrow("Preset not found");

Expand Down
15 changes: 7 additions & 8 deletions backend/__tests__/__integration__/dal/user.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1079,9 +1079,9 @@ describe("UserDal", () => {
await UserDAL.incrementTestActivity(user, 1712102400000);

//then
const read = (await UserDAL.getUser(user.uid, "")).testActivity || {};
const read = (await UserDAL.getUser(user.uid, "")).testActivity ?? {};
expect(read).toHaveProperty("2024");
const year2024 = read["2024"] as any;
const year2024 = read["2024"] as number[];
expect(year2024).toHaveLength(94);
//fill previous days with null
expect(year2024.slice(0, 93)).toEqual(new Array(93).fill(null));
Expand All @@ -1097,9 +1097,9 @@ describe("UserDal", () => {
await UserDAL.incrementTestActivity(user, 1712102400000);

//then
const read = (await UserDAL.getUser(user.uid, "")).testActivity || {};
const read = (await UserDAL.getUser(user.uid, "")).testActivity ?? {};
expect(read).toHaveProperty("2024");
const year2024 = read["2024"] as any;
const year2024 = read["2024"] as number[];
expect(year2024).toHaveLength(94);

expect(year2024[0]).toBeNull();
Expand All @@ -1117,7 +1117,7 @@ describe("UserDal", () => {
await UserDAL.incrementTestActivity(user, 1712102400000);

//then
const read = (await UserDAL.getUser(user.uid, "")).testActivity || {};
const read = (await UserDAL.getUser(user.uid, "")).testActivity ?? {};
const year2024 = read["2024"] as any;
expect(year2024[93]).toEqual(2);
});
Expand Down Expand Up @@ -1581,7 +1581,7 @@ describe("UserDal", () => {
const count = 100;
const calls = new Array(count)
.fill(0)
.map(() =>
.map(async () =>
UserDAL.updateInbox(
user.uid,
[rewardOne.id, rewardTwo.id, rewardThree.id],
Expand Down Expand Up @@ -2084,10 +2084,9 @@ describe("UserDal", () => {
it("should clear streak hour offset", async () => {
// given
const { uid } = await UserTestData.createUser({
//@ts-expect-error
streak: {
hourOffset: 1,
},
} as any,
});

// when
Expand Down
2 changes: 1 addition & 1 deletion backend/__tests__/__integration__/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ export async function cleanupKeys(prefix: string): Promise<void> {
// oxlint-disable-next-line no-non-null-assertion
const connection = getConnection()!;
const keys = await connection.keys(`${prefix}*`);
await Promise.all(keys?.map((it) => connection.del(it)));
await Promise.all(keys?.map(async (it) => connection.del(it)));
}
11 changes: 5 additions & 6 deletions backend/__tests__/__integration__/setup-integration-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { getConnection } from "../../src/init/redis";

process.env["MODE"] = "dev";

let db: Db;
let client: MongoClient;
let db: Db | undefined;
let client: MongoClient | undefined;

beforeAll(async () => {
client = new MongoClient(process.env["TEST_DB_URL"] as string);
Expand All @@ -15,9 +15,9 @@ beforeAll(async () => {

vi.mock("../../src/init/db", () => ({
__esModule: true,
getDb: (): Db => db,
getDb: (): Db => db as Db,
collection: <T>(name: string): Collection<WithId<T>> =>
db.collection<WithId<T>>(name),
(db as Db).collection<WithId<T>>(name),
close: () => {
//
},
Expand All @@ -35,9 +35,8 @@ afterEach(async () => {

afterAll(async () => {
await client?.close();
// @ts-ignore

db = undefined;
//@ts-ignore
client = undefined;

await getConnection()?.quit();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ describe("Daily Leaderboards", () => {
await Promise.all(
new Array(maxResults - 1)
.fill(0)
.map(() => givenResult({ wpm: 20 + Math.random() * 100 })),
.map(async () => givenResult({ wpm: 20 + Math.random() * 100 })),
);
expect(
await lb.getResults(0, 5, dailyLeaderboardsConfig, true),
Expand Down
39 changes: 25 additions & 14 deletions backend/__tests__/__testData__/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,28 @@ export async function mockAuthenticateWithApeKey(
return base64UrlEncode(`${apeKeyId}.${apiKey}`);
}

export function mockBearerAuthentication(uid: string) {
export type BearerAuthenticationMock = {
/**
* Reset the mock and return a default token. Call this method in the `beforeEach` of all tests.
*/
beforeEach: () => void;
/**
* Reset the mock results in the authentication to fail.
*/
noAuth: () => void;
/**
* verify the authentication has been called
*/
expectToHaveBeenCalled: () => void;
/**
* modify the token returned by the mock. This can be used to e.g. return a stale token.
* @param customize
*/
modifyToken: (customize: Partial<DecodedIdToken>) => void;
};
export function mockBearerAuthentication(
uid: string,
): BearerAuthenticationMock {
const mockDecodedToken = {
uid,
email: "newuser@mail.com",
Expand All @@ -49,29 +70,19 @@ export function mockBearerAuthentication(uid: string) {
const verifyIdTokenMock = vi.spyOn(AuthUtils, "verifyIdToken");

return {
/**
* Reset the mock and return a default token. Call this method in the `beforeEach` of all tests.
*/
beforeEach: (): void => {
verifyIdTokenMock.mockClear();
verifyIdTokenMock.mockResolvedValue(mockDecodedToken);
},
/**
* Reset the mock results in the authentication to fail.
*/

noAuth: (): void => {
verifyIdTokenMock.mockClear();
},
/**
* verify the authentication has been called
*/

expectToHaveBeenCalled: (): void => {
expect(verifyIdTokenMock).toHaveBeenCalled();
},
/**
* modify the token returned by the mock. This can be used to e.g. return a stale token.
* @param customize
*/

modifyToken: (customize: Partial<DecodedIdToken>): void => {
verifyIdTokenMock.mockClear();
verifyIdTokenMock.mockResolvedValue({
Expand Down
9 changes: 7 additions & 2 deletions backend/__tests__/__testData__/controller-test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import request from "supertest";
import app from "../../src/app";
import { ObjectId } from "mongodb";
import { mockBearerAuthentication } from "./auth";
import { BearerAuthenticationMock, mockBearerAuthentication } from "./auth";
import { beforeEach } from "vitest";
import TestAgent from "supertest/lib/agent";

export function setup() {
export function setup(): {
mockApp: TestAgent;
uid: string;
mockAuth: BearerAuthenticationMock;
} {
const mockApp = request(app);
const uid = new ObjectId().toHexString();
const mockAuth = mockBearerAuthentication(uid);
Expand Down
3 changes: 1 addition & 2 deletions backend/__tests__/api/controllers/preset.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ describe("PresetController", () => {
showAverage: "off",
},
};
//@ts-expect-error
getPresetsMock.mockResolvedValue([presetOne, presetTwo]);
getPresetsMock.mockResolvedValue([presetOne, presetTwo] as any);

//WHEN
const { body } = await mockApp
Expand Down
13 changes: 6 additions & 7 deletions backend/__tests__/api/controllers/quotes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ describe("QuotesController", () => {
const getPartialUserMock = vi.spyOn(UserDal, "getPartialUser");
const logsAddLogMock = vi.spyOn(LogsDal, "addLog");

beforeEach(() => {
enableQuotes(true);
beforeEach(async () => {
await enableQuotes(true);

const user = { quoteMod: true, name: "Bob" } as any;
getPartialUserMock.mockClear().mockResolvedValue(user);
Expand Down Expand Up @@ -128,7 +128,6 @@ describe("QuotesController", () => {
describe("isSubmissionsEnabled", () => {
it("should return for quotes enabled without authentication", async () => {
//GIVEN
enableQuotes(true);

//WHEN
const { body } = await mockApp
Expand Down Expand Up @@ -202,7 +201,7 @@ describe("QuotesController", () => {
});
it("should fail if feature is disabled", async () => {
//GIVEN
enableQuotes(false);
await enableQuotes(false);

//WHEN
const { body } = await mockApp
Expand Down Expand Up @@ -755,8 +754,8 @@ describe("QuotesController", () => {
const verifyCaptchaMock = vi.spyOn(Captcha, "verify");
const createReportMock = vi.spyOn(ReportDal, "createReport");

beforeEach(() => {
enableQuoteReporting(true);
beforeEach(async () => {
await enableQuoteReporting(true);

verifyCaptchaMock.mockClear().mockResolvedValue(true);
createReportMock.mockClear().mockResolvedValue();
Expand Down Expand Up @@ -843,7 +842,7 @@ describe("QuotesController", () => {
});
it("should fail if feature is disabled", async () => {
//GIVEN
enableQuoteReporting(false);
await enableQuoteReporting(false);

//WHEN
const { body } = await mockApp
Expand Down
6 changes: 3 additions & 3 deletions backend/__tests__/api/controllers/result.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ describe("result controller test", () => {
it("should get results within regular limits for premium users even if premium is globally disabled", async () => {
//GIVEN
vi.spyOn(UserDal, "checkIfUserIsPremium").mockResolvedValue(true);
enablePremiumFeatures(false);
await enablePremiumFeatures(false);

//WHEN
await mockApp
Expand All @@ -225,7 +225,7 @@ describe("result controller test", () => {
it("should fail exceeding max limit for premium user if premium is globally disabled", async () => {
//GIVEN
vi.spyOn(UserDal, "checkIfUserIsPremium").mockResolvedValue(true);
enablePremiumFeatures(false);
await enablePremiumFeatures(false);

//WHEN
const { body } = await mockApp
Expand All @@ -241,7 +241,7 @@ describe("result controller test", () => {
it("should get results with regular limit as default for premium users if premium is globally disabled", async () => {
//GIVEN
vi.spyOn(UserDal, "checkIfUserIsPremium").mockResolvedValue(true);
enablePremiumFeatures(false);
await enablePremiumFeatures(false);

//WHEN
await mockApp
Expand Down
Loading
Loading