diff --git a/packages/graphql/api/customer.test.ts b/packages/graphql/api/customer.test.ts new file mode 100644 index 0000000..0b85a49 --- /dev/null +++ b/packages/graphql/api/customer.test.ts @@ -0,0 +1,110 @@ +import { beforeEach, describe, expect, it, Mock, vi } from 'vitest'; +import * as ApolloClient from '../apollo/client'; +import * as GQL from '../types'; +import { createOrUpdateUser } from './customer'; + +vi.mock('../apollo/client', () => ({ + getClientWithToken: vi.fn(), +})); + +const mockQuery = vi.fn(); +const mockMutate = vi.fn(); + +type ApolloResponse = { + data: TData; +}; + +describe('api/customer', () => { + describe('createOrUpdateUser', () => { + beforeEach(() => { + vi.clearAllMocks(); + (ApolloClient.getClientWithToken as Mock).mockResolvedValue({ + query: mockQuery, + mutate: mockMutate, + }); + }); + + const variables: GQL.CreateUserMutationVariables = { + name: 'John Doe', + phone: '1234567890', + telegramId: '1234567890', + }; + + const user: GQL.CustomerProfileFragment = { + __typename: 'Customer', + documentId: '123', + name: 'John Doe', + phone: '1234567890', + telegramId: '1234567890', + role: GQL.Enum_Customer_Role.Client, + masters: [], + }; + + it('create new user if it does not exist', async () => { + mockQuery.mockResolvedValueOnce({ + data: { + customers: [], + }, + }); + + const mockCreateResponse: ApolloResponse = { + data: { createCustomer: user }, + }; + mockMutate.mockResolvedValueOnce(mockCreateResponse); + + const result = await createOrUpdateUser(variables); + + expect(mockQuery).toHaveBeenCalledWith({ + query: GQL.GetUserByPhoneDocument, + variables, + }); + + expect(mockMutate).toHaveBeenCalledWith({ + mutation: GQL.CreateUserDocument, + variables, + }); + + expect(mockMutate).not.toHaveBeenCalledWith({ + mutation: GQL.UpdateCustomerProfileDocument, + variables, + }); + + expect(result).toEqual(mockCreateResponse); + }); + + it('update user if it exists', async () => { + mockQuery.mockResolvedValueOnce({ + data: { + customers: [user], + }, + }); + + const mockUpdateResponse: ApolloResponse = { + data: { updateCustomer: user }, + }; + mockMutate.mockResolvedValueOnce(mockUpdateResponse); + + const result = await createOrUpdateUser(variables); + + expect(mockQuery).toHaveBeenCalledWith({ + query: GQL.GetUserByPhoneDocument, + variables, + }); + + expect(mockMutate).toHaveBeenCalledWith({ + mutation: GQL.UpdateCustomerProfileDocument, + variables: { + documentId: user.documentId, + data: variables, + }, + }); + + expect(mockMutate).not.toHaveBeenCalledWith({ + mutation: GQL.CreateUserDocument, + variables, + }); + + expect(result).toEqual(mockUpdateResponse); + }); + }); +});