fe-middleware/test/imageService.test.ts

56 lines
2.0 KiB
TypeScript

import { afterAll, describe, expect, it, jest, mock, spyOn } from "bun:test";
import Image from "src/types/Image";
import request from "supertest";
import * as gelbooruApiService from "src/services/gelbooruApiService";
import * as botApiService from "src/services/botApiService";
import * as imageService from "src/services/imageService";
import app from "src/app";
import { response } from "express";
afterAll(() => {
jest.restoreAllMocks();
})
describe("the service is thread-safe", () => {
it("should not crash when multiple processes call the get() method with 1 remaining image in the queue", async () => {
const NUM_OF_REQUESTS = 110;
const getFn = spyOn(imageService, "get");
const promises = Array(NUM_OF_REQUESTS).fill(null)
.map(_ => request(app).get("/image"));
const responses = await Promise.all(promises);
expect(getFn).toHaveBeenCalledTimes(NUM_OF_REQUESTS);
responses.forEach(res => expect(res.status).toBe(200));
})
})
describe("endpoint gets a non repeated image", () => {
it("should return an image that is not in the response of the /images endpoint of the bot API", async () => {
const REPEATED_URL =
"https://fastly.picsum.photos/id/1/10/20.jpg?hmac=gY6PvUXFacKfYpBpTTVcNLxumpyMmoCamM-J5DOPwNc";
const UNIQUE_URL =
"https://fastly.picsum.photos/id/2/10/20.jpg?hmac=zy6lz21CuRIstr9ETx9h5AuoH50s_L2uIEct3dROpY8";
const gelbooruApiServiceGet = spyOn(gelbooruApiService, "get");
gelbooruApiServiceGet.mockImplementationOnce(async () => ({ posts: [{ url: UNIQUE_URL, tags: [] }] }));
gelbooruApiServiceGet.mockImplementation(async () => ({ posts: [{ url: REPEATED_URL, tags: [] }] }));
spyOn(botApiService, "getAll").mockImplementation(async () => ({
images: [
{
_id: "0",
url: REPEATED_URL,
status: "consumed",
tags: ["pokemon", "computer"],
__v: 0,
},
],
}));
const image: Image = await imageService.get();
expect(image.url).not.toBe(REPEATED_URL);
});
});