From c6c44d00fabcbcacdc3d5f894c64ffb5a9371333 Mon Sep 17 00:00:00 2001 From: Tai Sakuma Date: Thu, 14 Sep 2023 19:48:24 -0400 Subject: [PATCH] add an example test --- src/tests/__tests__/example/use-fetch.spec.ts | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/tests/__tests__/example/use-fetch.spec.ts diff --git a/src/tests/__tests__/example/use-fetch.spec.ts b/src/tests/__tests__/example/use-fetch.spec.ts new file mode 100644 index 0000000..586f97d --- /dev/null +++ b/src/tests/__tests__/example/use-fetch.spec.ts @@ -0,0 +1,47 @@ +import { ref } from "vue"; +import { describe, it, expect, vi, afterEach } from "vitest"; +import { useFetch } from "@vueuse/core"; + +global.fetch = vi.fn(); + +// https://runthatline.com/how-to-mock-fetch-api-with-vitest/ +// https://vueuse.org/core/useFetch/ + +describe("useFetch", () => { + type Response = Awaited>; + + // @ts-expect-error + const createResponse = (data: any): Response => ({ + json: () => new Promise((resolve) => resolve(data)), + ok: true, // https://github.com/vueuse/vueuse/blob/v10.4.1/packages/core/useFetch/index.ts#L471 + }); + + const responseData = [ + { + title: "Unit test", + done: false, + }, + ]; + + afterEach(() => { + vi.mocked(global.fetch).mockReset(); + }); + + it("should work", async () => { + vi.mocked(fetch).mockResolvedValue(createResponse(responseData)); + + const url = ref("https://jsonplaceholder.typicode.com/todos/1"); + + const { data, isFinished, then } = useFetch(url, { + refetch: true, + }).json(); + + expect(isFinished.value).toBe(false); + expect(data.value).toBeNull(); + await then(); + expect(isFinished.value).toBe(true); + expect(data.value).toStrictEqual(responseData); + + // console.log(global.fetch.mock.calls); + }); +});