|
| 1 | +import { describe, it, expect } from "vitest"; |
| 2 | +import { fileURLToPath } from "node:url"; |
| 3 | +import { setup, $fetch } from "@nuxt/test-utils/e2e"; |
| 4 | +import { beforeEach } from "vitest"; |
| 5 | +import { rm } from "node:fs/promises"; |
| 6 | + |
| 7 | +beforeEach(async () => { |
| 8 | + // await useStorage("shield").clear(); TODO waiting for https://github.com/nuxt/test-utils/issues/531 |
| 9 | + // this is a workaround to clean the storage |
| 10 | + const storagePath = fileURLToPath(new URL("../_testWithRoutesShield", import.meta.url)); |
| 11 | + await rm(storagePath, { recursive: true, force: true }); |
| 12 | +}); |
| 13 | + |
| 14 | +describe("shield", async () => { |
| 15 | + await setup({ |
| 16 | + rootDir: fileURLToPath(new URL("./fixtures/withroutes", import.meta.url)), |
| 17 | + }); |
| 18 | + |
| 19 | + it("respond to api call 2 times (limit.max, limit.duration) and rejects the 3rd call if the route matches the routes option", async () => { |
| 20 | + // req.count = 1 |
| 21 | + let response = await $fetch("/api/v3/example?c=1/1", { |
| 22 | + method: "GET", |
| 23 | + retryStatusCodes: [], |
| 24 | + }); |
| 25 | + expect((response as any).name).toBe("Gauranga"); |
| 26 | + |
| 27 | + // req.count = 2 |
| 28 | + response = await $fetch("/api/v3/example?c=1/2", { |
| 29 | + method: "GET", |
| 30 | + retryStatusCodes: [], |
| 31 | + }); |
| 32 | + expect((response as any).name).toBe("Gauranga"); |
| 33 | + |
| 34 | + try { |
| 35 | + // req.count = 3 |
| 36 | + // as limit.max = 2, this should throw 429 and ban for 3 seconds (limit.ban) |
| 37 | + expect(async () => |
| 38 | + $fetch("/api/v3/example?c=1/3", { method: "GET", retryStatusCodes: [] }) |
| 39 | + ).rejects.toThrowError(); |
| 40 | + } catch (err) { |
| 41 | + const typedErr = err as { statusCode: number; statusMessage: string }; |
| 42 | + expect(typedErr.statusCode).toBe(429); |
| 43 | + expect(typedErr.statusMessage).toBe("Leave me alone"); |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + it("respond to api call 2 times (limit.max, limit.duration) and accept the 3rd call if the route does not matches the routes option", async () => { |
| 48 | + // req.count = 1 |
| 49 | + let response = await $fetch("/api/v2/example?c=2/1", { |
| 50 | + method: "GET", |
| 51 | + retryStatusCodes: [], |
| 52 | + }); |
| 53 | + expect((response as any).name).toBe("Gauranga"); |
| 54 | + |
| 55 | + // req.count = 2 |
| 56 | + response = await $fetch("/api/v2/example?c=2/2", { |
| 57 | + method: "GET", |
| 58 | + retryStatusCodes: [], |
| 59 | + }); |
| 60 | + expect((response as any).name).toBe("Gauranga"); |
| 61 | + |
| 62 | + // req.count = 3 |
| 63 | + response = await $fetch("/api/v2/example?c=2/3", { |
| 64 | + method: "GET", |
| 65 | + retryStatusCodes: [], |
| 66 | + }); |
| 67 | + expect((response as any).name).toBe("Gauranga"); |
| 68 | + }); |
| 69 | + |
| 70 | + |
| 71 | +}); |
0 commit comments