|
| 1 | +import { GraphQLResolveInfo } from 'graphql'; |
| 2 | +import { MiddlewareContext, NextFn } from '../../lib/interfaces'; |
| 3 | + |
| 4 | +export const testMiddleware = async (ctx: MiddlewareContext, next: NextFn) => { |
| 5 | + let logData: MiddlewareContext = { |
| 6 | + source: ctx.source, |
| 7 | + args: ctx.args, |
| 8 | + context: ctx.context, |
| 9 | + }; |
| 10 | + |
| 11 | + if (ctx.info) { |
| 12 | + logData = { |
| 13 | + ...logData, |
| 14 | + info: ctx.info, |
| 15 | + }; |
| 16 | + } |
| 17 | + |
| 18 | + return next(); |
| 19 | +}; |
| 20 | + |
| 21 | +describe('testMiddleware', () => { |
| 22 | + let mockContext: MiddlewareContext; |
| 23 | + let mockNext: NextFn; |
| 24 | + |
| 25 | + beforeEach(async () => { |
| 26 | + mockContext = { |
| 27 | + source: {}, |
| 28 | + args: {}, |
| 29 | + context: {}, |
| 30 | + info: { |
| 31 | + path: { typename: 'TestType', key: 'testField' }, |
| 32 | + } as GraphQLResolveInfo, |
| 33 | + }; |
| 34 | + |
| 35 | + mockNext = jest.fn().mockResolvedValue('next result'); |
| 36 | + }); |
| 37 | + |
| 38 | + afterEach(() => { |
| 39 | + jest.clearAllMocks(); |
| 40 | + }); |
| 41 | + |
| 42 | + it('should log the context and call next function', async () => { |
| 43 | + const result = await testMiddleware(mockContext, mockNext); |
| 44 | + |
| 45 | + expect(mockNext).toHaveBeenCalled(); |
| 46 | + expect(result).toBe('next result'); |
| 47 | + }); |
| 48 | + |
| 49 | + it('should handle undefined info object', async () => { |
| 50 | + mockContext.info = undefined; |
| 51 | + |
| 52 | + await testMiddleware(mockContext, mockNext); |
| 53 | + |
| 54 | + expect(mockNext).toHaveBeenCalled(); |
| 55 | + }); |
| 56 | + |
| 57 | + it('should handle null info object', async () => { |
| 58 | + mockContext.info = null; |
| 59 | + |
| 60 | + await testMiddleware(mockContext, mockNext); |
| 61 | + |
| 62 | + expect(mockNext).toHaveBeenCalled(); |
| 63 | + }); |
| 64 | +}); |
0 commit comments