test(api-keys): add unit tests for ApiKeysController and ApiKeysRepository with mocked dependencies
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { DatabaseService } from "../../database/database.service";
|
||||
import { ApiKeysRepository } from "./api-keys.repository";
|
||||
|
||||
describe("ApiKeysRepository", () => {
|
||||
let repository: ApiKeysRepository;
|
||||
let _databaseService: DatabaseService;
|
||||
|
||||
const mockDb = {
|
||||
insert: jest.fn().mockReturnThis(),
|
||||
values: jest.fn().mockReturnThis(),
|
||||
select: jest.fn().mockReturnThis(),
|
||||
from: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
update: jest.fn().mockReturnThis(),
|
||||
set: jest.fn().mockReturnThis(),
|
||||
returning: jest.fn().mockReturnThis(),
|
||||
limit: jest.fn().mockReturnThis(),
|
||||
execute: jest.fn(),
|
||||
};
|
||||
|
||||
const wrapWithThen = (obj: any) => {
|
||||
obj.then = function (onFulfilled: any) {
|
||||
const result = this.execute();
|
||||
return Promise.resolve(result).then(onFulfilled);
|
||||
};
|
||||
return obj;
|
||||
};
|
||||
wrapWithThen(mockDb);
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ApiKeysRepository,
|
||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
repository = module.get<ApiKeysRepository>(ApiKeysRepository);
|
||||
_databaseService = module.get<DatabaseService>(DatabaseService);
|
||||
});
|
||||
|
||||
it("should create an api key", async () => {
|
||||
(mockDb.execute as jest.Mock).mockResolvedValue([{ id: "1" }]);
|
||||
await repository.create({
|
||||
userId: "u1",
|
||||
name: "n",
|
||||
prefix: "p",
|
||||
keyHash: "h",
|
||||
});
|
||||
expect(mockDb.insert).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should find all keys for user", async () => {
|
||||
(mockDb.execute as jest.Mock).mockResolvedValue([{ id: "1" }]);
|
||||
const result = await repository.findAll("u1");
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("should revoke a key", async () => {
|
||||
(mockDb.execute as jest.Mock).mockResolvedValue([
|
||||
{ id: "1", isActive: false },
|
||||
]);
|
||||
const result = await repository.revoke("u1", "k1");
|
||||
expect(result[0].isActive).toBe(false);
|
||||
});
|
||||
|
||||
it("should find active by hash", async () => {
|
||||
(mockDb.execute as jest.Mock).mockResolvedValue([{ id: "1" }]);
|
||||
const result = await repository.findActiveByKeyHash("h");
|
||||
expect(result.id).toBe("1");
|
||||
});
|
||||
|
||||
it("should update last used", async () => {
|
||||
(mockDb.execute as jest.Mock).mockResolvedValue([{ id: "1" }]);
|
||||
await repository.updateLastUsed("1");
|
||||
expect(mockDb.update).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user