1// @vitest-environment jsdom
2
3import { h } from 'preact';
4import { act, cleanup, render } from '@testing-library/preact';
5import { pipe, fromValue, delay } from 'wonka';
6import { vi, expect, it, beforeEach, describe, afterEach, Mock } from 'vitest';
7
8import { Provider } from '../context';
9import { Mutation } from './Mutation';
10
11const mock = {
12 executeMutation: vi.fn(() =>
13 pipe(fromValue({ data: 1, error: 2, extensions: { i: 1 } }), delay(200))
14 ),
15};
16const client = mock as { executeMutation: Mock };
17const query = 'mutation Example { example }';
18
19describe('Mutation', () => {
20 beforeEach(() => {
21 vi.useFakeTimers();
22
23 vi.spyOn(globalThis.console, 'error').mockImplementation(() => {
24 // do nothing
25 });
26 });
27
28 afterEach(() => {
29 cleanup();
30 });
31
32 it('Should execute the mutation', () => {
33 // eslint-disable-next-line
34 let execute = () => {},
35 props = {};
36 const Test = () => h('p', {}, 'hi');
37 const App = () => {
38 // @ts-ignore
39 return h(Provider, {
40 value: client,
41 children: [
42 h(
43 Mutation as any,
44 { query },
45 ({ data, fetching, error, executeMutation }) => {
46 execute = executeMutation;
47 props = { data, fetching, error };
48 // @ts-ignore
49 return h(Test, {});
50 }
51 ),
52 ],
53 });
54 };
55 render(h(App, {}));
56 expect(client.executeMutation).toBeCalledTimes(0);
57 expect(props).toStrictEqual({
58 data: undefined,
59 fetching: false,
60 error: undefined,
61 });
62
63 act(() => {
64 execute();
65 });
66
67 expect(props).toStrictEqual({
68 data: undefined,
69 fetching: true,
70 error: undefined,
71 });
72
73 act(() => {
74 vi.advanceTimersByTime(400);
75 });
76
77 expect(props).toStrictEqual({ data: 1, fetching: false, error: 2 });
78 });
79});