Skip to content

Commit

Permalink
add an example test
Browse files Browse the repository at this point in the history
  • Loading branch information
TaiSakuma committed Sep 14, 2023
1 parent dc26d7e commit c6c44d0
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/tests/__tests__/example/use-fetch.spec.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof global.fetch>>;

// @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);
});
});

0 comments on commit c6c44d0

Please sign in to comment.