|
| 1 | +import { DefaultError, QueryClient } from '@tanstack/query-core'; |
| 2 | +import { describe, expect, it, vi } from 'vitest'; |
| 3 | + |
| 4 | +import { MobxMutation } from './mobx-mutation'; |
| 5 | +import { MobxMutationConfig } from './mobx-mutation.types'; |
| 6 | + |
| 7 | +class MobxMutationMock< |
| 8 | + TData = unknown, |
| 9 | + TVariables = void, |
| 10 | + TError = DefaultError, |
| 11 | + TContext = unknown, |
| 12 | +> extends MobxMutation<TData, TVariables, TError, TContext> { |
| 13 | + spies = { |
| 14 | + mutationFn: null as unknown as ReturnType<typeof vi.fn>, |
| 15 | + dispose: vi.fn(), |
| 16 | + reset: vi.fn(), |
| 17 | + onDone: vi.fn(), |
| 18 | + onError: vi.fn(), |
| 19 | + }; |
| 20 | + |
| 21 | + constructor( |
| 22 | + options: Omit< |
| 23 | + MobxMutationConfig<TData, TVariables, TError, TContext>, |
| 24 | + 'queryClient' |
| 25 | + >, |
| 26 | + ) { |
| 27 | + const mutationFn = vi.fn((...args: any[]) => { |
| 28 | + // @ts-ignore |
| 29 | + const result = options.mutationFn?.(...args); |
| 30 | + return result; |
| 31 | + }); |
| 32 | + super({ |
| 33 | + ...options, |
| 34 | + queryClient: new QueryClient({}), |
| 35 | + // @ts-ignore |
| 36 | + mutationFn, |
| 37 | + }); |
| 38 | + |
| 39 | + this.spies.mutationFn = mutationFn as any; |
| 40 | + |
| 41 | + this.onDone(this.spies.onDone); |
| 42 | + this.onError(this.spies.onError); |
| 43 | + } |
| 44 | + |
| 45 | + reset(): void { |
| 46 | + const result = super.reset(); |
| 47 | + this.spies.reset.mockReturnValue(result)(); |
| 48 | + return result; |
| 49 | + } |
| 50 | + |
| 51 | + dispose(): void { |
| 52 | + const result = super.dispose(); |
| 53 | + this.spies.dispose.mockReturnValue(result)(); |
| 54 | + return result; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +describe('MobxMutation', () => { |
| 59 | + it('should call mutationFn', async () => { |
| 60 | + const mobxMutation = new MobxMutationMock({ |
| 61 | + mutationKey: ['test'], |
| 62 | + mutationFn: async () => {}, |
| 63 | + }); |
| 64 | + |
| 65 | + await mobxMutation.mutate(); |
| 66 | + |
| 67 | + expect(mobxMutation.spies.mutationFn).toHaveBeenCalled(); |
| 68 | + }); |
| 69 | + |
| 70 | + it('should have result with finished data', async () => { |
| 71 | + const mobxMutation = new MobxMutationMock({ |
| 72 | + mutationKey: ['test'], |
| 73 | + mutationFn: async () => { |
| 74 | + return 'OK'; |
| 75 | + }, |
| 76 | + }); |
| 77 | + |
| 78 | + await mobxMutation.mutate(); |
| 79 | + |
| 80 | + expect(mobxMutation.result).toStrictEqual({ |
| 81 | + ...mobxMutation.result, |
| 82 | + context: undefined, |
| 83 | + data: 'OK', |
| 84 | + error: null, |
| 85 | + failureCount: 0, |
| 86 | + failureReason: null, |
| 87 | + isError: false, |
| 88 | + isIdle: false, |
| 89 | + isPaused: false, |
| 90 | + isPending: false, |
| 91 | + isSuccess: true, |
| 92 | + status: 'success', |
| 93 | + variables: undefined, |
| 94 | + }); |
| 95 | + }); |
| 96 | +}); |
0 commit comments