1import { OperationResult, OperationResultSource } from '@urql/core';
2import { readonly } from 'vue';
3import { vi, expect, it, beforeEach, describe } from 'vitest';
4
5vi.mock('./useClient.ts', async () => {
6 const { ref } = await vi.importActual<typeof import('vue')>('vue');
7 return {
8 __esModule: true,
9 ...((await vi.importActual('./useClient.ts')) as object),
10 useClient: () => ref(client),
11 };
12});
13
14import { makeSubject } from 'wonka';
15import { createClient, gql } from '@urql/core';
16import { useMutation } from './useMutation';
17
18const client = createClient({ url: '/graphql', exchanges: [] });
19
20beforeEach(() => {
21 vi.resetAllMocks();
22});
23
24describe('useMutation', () => {
25 it('provides an execute method that resolves a promise', async () => {
26 const subject = makeSubject<any>();
27 const clientMutation = vi
28 .spyOn(client, 'executeMutation')
29 .mockImplementation(
30 () => subject.source as OperationResultSource<OperationResult>
31 );
32
33 const mutation = useMutation(gql`
34 mutation {
35 test
36 }
37 `);
38
39 expect(readonly(mutation)).toMatchObject({
40 data: undefined,
41 stale: false,
42 fetching: false,
43 error: undefined,
44 extensions: undefined,
45 operation: undefined,
46 executeMutation: expect.any(Function),
47 });
48
49 const promise = mutation.executeMutation({ test: true });
50
51 expect(mutation.fetching.value).toBe(true);
52 expect(mutation.stale.value).toBe(false);
53 expect(mutation.error.value).toBe(undefined);
54
55 expect(clientMutation).toHaveBeenCalledTimes(1);
56
57 subject.next({ data: { test: true }, stale: false });
58
59 await promise;
60 expect(mutation.fetching.value).toBe(false);
61 expect(mutation.stale.value).toBe(false);
62 expect(mutation.error.value).toBe(undefined);
63 expect(mutation.data.value).toHaveProperty('test', true);
64 });
65});