fe-middleware/test/imageService.test.ts

55 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-04-21 10:53:04 +00:00
import { afterEach, describe, expect, it, jest, spyOn } from "bun:test";
import app from "src/app";
import * as botApiService from "src/services/botApiService";
2024-04-21 10:53:04 +00:00
import * as gelbooruApiService from "src/services/gelbooruApiService";
import * as imageService from "src/services/imageService";
2024-04-21 10:53:04 +00:00
import Image from "src/types/Image";
import request from "supertest";
2024-04-21 10:49:38 +00:00
afterEach(() => {
jest.restoreAllMocks();
})
describe("the service is thread-safe", () => {
2024-04-21 10:49:38 +00:00
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", () => {
2024-04-17 18:04:43 +00:00
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,
2024-04-17 18:04:43 +00:00
},
],
2024-04-17 18:04:43 +00:00
}));
const image: Image = await imageService.get();
2024-04-17 18:04:43 +00:00
expect(image.url).not.toBe(REPEATED_URL);
});
});