diff --git a/apps/users-application/src/users/users.resolver.spec.ts b/apps/users-application/src/users/users.resolver.spec.ts new file mode 100644 index 0000000..e962238 --- /dev/null +++ b/apps/users-application/src/users/users.resolver.spec.ts @@ -0,0 +1,64 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { UsersResolver } from './users.resolver'; +import { UsersService } from './users.service'; +import { User } from './models/user.model'; + +describe('UsersResolver', () => { + let resolver: UsersResolver; + let service: UsersService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ + UsersResolver, + { + provide: UsersService, + useValue: { + findById: jest.fn(), + }, + }, + ], + }).compile(); + + resolver = module.get(UsersResolver); + service = module.get(UsersService); + }); + + it('should be defined', () => { + expect(resolver).toBeDefined(); + }); + + describe('getUser', () => { + it('should return a user by id', () => { + const user: User = { id: 1, name: 'John Doe' }; + jest.spyOn(service, 'findById').mockReturnValue(user); + + expect(resolver.getUser(1)).toEqual(user); + expect(service.findById).toHaveBeenCalledWith(1); + }); + + it('should return undefined if user not found', () => { + jest.spyOn(service, 'findById').mockReturnValue(undefined); + + expect(resolver.getUser(1)).toBeUndefined(); + expect(service.findById).toHaveBeenCalledWith(1); + }); + }); + + describe('resolveReference', () => { + it('should return a user by reference id', () => { + const user: User = { id: 1, name: 'John Doe' }; + jest.spyOn(service, 'findById').mockReturnValue(user); + + expect(resolver.resolveReference({ __typename: 'User', id: 1 })).toEqual(user); + expect(service.findById).toHaveBeenCalledWith(1); + }); + + it('should return undefined if user not found by reference id', () => { + jest.spyOn(service, 'findById').mockReturnValue(undefined); + + expect(resolver.resolveReference({ __typename: 'User', id: 1 })).toBeUndefined(); + expect(service.findById).toHaveBeenCalledWith(1); + }); + }); +}); \ No newline at end of file diff --git a/apps/users-application/src/users/users.resolver.ts b/apps/users-application/src/users/users.resolver.ts new file mode 100644 index 0000000..04d7704 --- /dev/null +++ b/apps/users-application/src/users/users.resolver.ts @@ -0,0 +1,22 @@ +import { Args, ID, Query, Resolver, ResolveReference } from '@nestjs/graphql'; + +import { User } from './models/user.model'; +import { UsersService } from './users.service'; + +@Resolver(() => User) +export class UsersResolver { + constructor(private usersService: UsersService) {} + + @Query() + getUser(@Args({ name: 'id', type: () => ID }) id: number): User | undefined { + return this.usersService.findById(id); + } + + @ResolveReference() + resolveReference(reference: { + __typename: string; + id: number; + }): User | undefined { + return this.usersService.findById(reference.id); + } +}