Skip to content

Commit

Permalink
fix: random tests in api (#208)
Browse files Browse the repository at this point in the history
  • Loading branch information
leosayous21 authored Jul 11, 2023
1 parent 679b8d2 commit a76c039
Show file tree
Hide file tree
Showing 9 changed files with 243 additions and 203 deletions.
1 change: 1 addition & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const createJestConfig = nextJest({
const customJestConfig = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
testEnvironment: "jest-environment-jsdom",
testTimeout: 20000,
};

process.env = {
Expand Down
Binary file added space-configs/images/space_test_400x400.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
80 changes: 80 additions & 0 deletions src/app/api/zk-badge/image/[tokenId]/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { SpaceConfig } from "@/space-configs/types";
import { Network } from "@/src/libs/contracts/networks";
import { AuthType } from "@sismo-core/sismo-connect-server";

export const spaceMockWithZkBadge: SpaceConfig = {
metadata: {
slug: "space",
name: "Space",
description: "Space description",
image: "space.png",
socialLinks: [
{
type: "link",
link: "https://www.space.com",
},
],
},
apps: [
{
type: "zkBadge",
metadata: {
name: "ZK Badge name",
slug: "sismo-zk-badge-slug",
description: "Zk badge test description",
tags: ["Badge"],
image: "image.png",
createdAt: new Date("2023-07-03T18:00"),
},
sismoConnectRequest: {
appId: "0x4",
authRequests: [{ authType: AuthType.VAULT }],
claimRequests: [{ groupId: "0x04" }],
},
templateConfig: {
step2CtaText: "zkBadge step2CtaText",
tokenId: "40000001",
badgeMetadata: {
name: "Badge name",
description: "Badge description",
image: "space_test_400x400.png",
},
chains: [
{
name: Network.Gnosis,
},
],
},
},
{
type: "zkBadge",
metadata: {
name: "ZK Badge name not existing",
slug: "sismo-zk-badge-slug-not-existing",
description: "Zk badge test description",
tags: ["Badge"],
image: "image.png",
createdAt: new Date("2023-07-03T18:00"),
},
sismoConnectRequest: {
appId: "0x4",
authRequests: [{ authType: AuthType.VAULT }],
claimRequests: [{ groupId: "0x04" }],
},
templateConfig: {
step2CtaText: "zkBadge step2CtaText",
tokenId: "40000002",
badgeMetadata: {
name: "Badge name",
description: "Badge description",
image: "un_existing_image_400x400.png",
},
chains: [
{
name: Network.Gnosis,
},
],
},
},
],
};
65 changes: 16 additions & 49 deletions src/app/api/zk-badge/image/[tokenId]/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,34 @@
/**
* @jest-environment node
*/
import { spaceMockWithZkBadge } from "./mocks";
import ServiceFactory from "@/src/services/service-factory/service-factory";
import { GET } from "../../image/[tokenId]/route";
import { spaceMock1, spaceMock2 } from "@/src/services/spaces-service/tests/spaces-mock";
import fs from 'fs';
import path from 'path';

describe("GET /api/zk-badge/image/[tokenId]", () => {
beforeEach(() => {
ServiceFactory.reset();
ServiceFactory.getSpaceConfigs([spaceMockWithZkBadge]);
});

describe('GET /api/zk-badge/image/[tokenId]', () => {

beforeEach(() => {
let spacesService = ServiceFactory.getSpacesService();
const configs = [
spaceMock1,
spaceMock2
]
spacesService.updateConfigs(configs);
})

afterEach(() => {
let configs = ServiceFactory.getSpaceConfigs();
let spacesService = ServiceFactory.getSpacesService();
spacesService.updateConfigs(configs);
jest.clearAllMocks();
})

it('should return an error response if no badge is found', async () => {
it("should return an error response if no badge is found", async () => {
const params = { tokenId: "1234" };
const response = await GET(null, { params });
const data = await response.json();
expect(data).toEqual({ error: 'No badge found for tokenId: 1234' });
expect(data).toEqual({ error: "No badge found for tokenId: 1234" });
});

it('should return an error response if no badge image is found', async () => {
it("should return an image response if a badge is found", async () => {
const params = { tokenId: "40000001" };
const response = await GET(null, { params });
const data = await response.json();
expect(data).toEqual({ error: 'No badge image found for tokenId: 40000001' });
expect(response.status).toEqual(200);
expect(response.headers.get("Content-Type")).toEqual("image/jpeg");
});

it('should return an image response if a badge is found', async () => {
jest.spyOn(fs, 'readFileSync');

const params = { tokenId: "40000001" };
const dummyImageBuffer = Buffer.from([0, 1, 2, 3, 4, 5]);
const imagePath = path.join(process.cwd(), '/space-configs/images/image.png');

(fs.readFileSync as jest.Mock).mockImplementation((path) => {
if (path === imagePath) {
return dummyImageBuffer;
}
});

it("should return an error response if no badge image is found", async () => {
const params = { tokenId: "40000002" };
const response = await GET(null, { params });

const reader = response.body.getReader();
const result = await reader.read();

const data = Buffer.from(result.value);

expect(Buffer.compare(data, dummyImageBuffer)).toEqual(0);
expect(response.status).toEqual(200);
expect(response.headers.get('Content-Type')).toEqual('image/jpeg');
const data = await response.json();
expect(data).toEqual({ error: "No image found for badge tokenId: 40000002" });
});
});
});
58 changes: 23 additions & 35 deletions src/app/api/zk-badge/image/[tokenId]/route.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,29 @@
import { error404Response } from "@/src/libs/helper/api";
import ServiceFactory from "@/src/services/service-factory/service-factory";
import { ZkBadgeAppType } from "@/src/services/spaces-service";
import fs from 'fs';
import fs from "fs";
import { NextResponse } from "next/server";
import path from 'path';

export async function GET(req: Request, { params }: { params: { tokenId: string } }) {
const tokenId = params.tokenId;
const spacesService = ServiceFactory.getSpacesService();
let apps = await spacesService.getApps();
apps = apps.filter(app => app.type === "zkBadge") ;
const badge = (apps as ZkBadgeAppType[]).find(app => app.tokenId === tokenId);
if (!badge) {
return NextResponse.json({
error: `No badge found for tokenId: ${tokenId}`
})
}
const tokenId = params.tokenId;
const spacesService = ServiceFactory.getSpacesService();
let apps = await spacesService.getApps();
apps = apps.filter((app) => app.type === "zkBadge");
const badge = (apps as ZkBadgeAppType[]).find((app) => app.tokenId === tokenId);
if (!badge) {
return error404Response(`No badge found for tokenId: ${tokenId}`);
}

let readableStream;
try {
const imagePath = path.join(process.cwd(), `/space-configs/images/${badge.badgeMetadata.image}`);
const file = fs.readFileSync(imagePath);
readableStream = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(file));
controller.close();
}
});
} catch (e) {
return NextResponse.json({
error: `No badge image found for tokenId: ${tokenId}`
})
}

return new NextResponse(readableStream, {
status: 200,
headers: {
'Content-Type': 'image/jpeg'
},
})
}
try {
const imagePath = `${__dirname}/../../../../../../space-configs/images/${badge.badgeMetadata.image}`;
const file = fs.readFileSync(imagePath);
return new NextResponse(file, {
status: 200,
headers: {
"Content-Type": "image/jpeg",
},
});
} catch (e) {
return error404Response(`No image found for badge tokenId: ${tokenId}`);
}
}
Loading

2 comments on commit a76c039

@vercel
Copy link

@vercel vercel bot commented on a76c039 Jul 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on a76c039 Jul 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.