import { afterEach, describe, expect, it, jest, spyOn } from "bun:test"; import app from "src/app"; import * as botApiService from "src/services/botApiService"; import * as gelbooruApiService from "src/services/gelbooruApiService"; import * as imageService from "src/services/imageService"; import Image from "src/types/Image"; import request from "supertest"; afterEach(() => { jest.restoreAllMocks(); }) describe("the service is thread-safe", () => { it("should not crash when multiple processes call the get() method simultaneously", 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); }); });