|
| 1 | +import { DocumentOptions } from '@vulcan-sql/core'; |
| 2 | +import { DocServerMiddleware, DocumentServer } from '@vulcan-sql/serve'; |
| 3 | +import * as compose from 'koa-compose'; |
| 4 | +import * as sinon from 'ts-sinon'; |
| 5 | + |
| 6 | +describe('Test doc server middlewares', () => { |
| 7 | + let mockDocServer: Record<string, sinon.StubbedInstance<DocumentServer<any>>>; |
| 8 | + let mockOption: DocumentOptions; |
| 9 | + const mockDocServerFactory = (name: string) => mockDocServer[name]; |
| 10 | + |
| 11 | + beforeEach(() => { |
| 12 | + mockDocServer = { |
| 13 | + m1: sinon.stubInterface<DocumentServer>(), |
| 14 | + m2: sinon.stubInterface<DocumentServer>(), |
| 15 | + m3: sinon.stubInterface<DocumentServer>(), |
| 16 | + }; |
| 17 | + mockOption = new DocumentOptions({ |
| 18 | + server: ['m1', 'm2'], |
| 19 | + }); |
| 20 | + }); |
| 21 | + |
| 22 | + it('Should active corresponding document servers', async () => { |
| 23 | + // Arrange |
| 24 | + const middleware = new DocServerMiddleware( |
| 25 | + {}, |
| 26 | + '', |
| 27 | + mockDocServerFactory, |
| 28 | + mockOption |
| 29 | + ); |
| 30 | + // Act |
| 31 | + await middleware.activate(); |
| 32 | + // Assert |
| 33 | + expect(mockDocServer['m1'].activate?.called).toBeTruthy(); |
| 34 | + expect(mockDocServer['m2'].activate?.called).toBeTruthy(); |
| 35 | + expect(mockDocServer['m3'].activate?.called).toBeFalsy(); |
| 36 | + }); |
| 37 | + |
| 38 | + it('Should execute middleware with correct order', async () => { |
| 39 | + // mid1 -> mid2(m1 -> m2) -> mid3 -> | next | -> mid3 -> mid2(m2 -> m1) -> mid1 |
| 40 | + // 1 -> 2 -> 3 -> 4 -> -> 5 -> 6 -> 7 -> 8 |
| 41 | + // Arrange |
| 42 | + const executeOrder: number[] = []; |
| 43 | + const mid1 = async (context: any, next: any) => { |
| 44 | + executeOrder.push(1); |
| 45 | + await next(); |
| 46 | + executeOrder.push(8); |
| 47 | + }; |
| 48 | + mockDocServer['m1'].handle.callsFake(async (context, next) => { |
| 49 | + executeOrder.push(2); |
| 50 | + await next(); |
| 51 | + executeOrder.push(7); |
| 52 | + }); |
| 53 | + mockDocServer['m2'].handle.callsFake(async (context, next) => { |
| 54 | + executeOrder.push(3); |
| 55 | + await next(); |
| 56 | + executeOrder.push(6); |
| 57 | + }); |
| 58 | + const mid2 = new DocServerMiddleware( |
| 59 | + {}, |
| 60 | + '', |
| 61 | + mockDocServerFactory, |
| 62 | + mockOption |
| 63 | + ); |
| 64 | + const mid3 = async (context: any, next: any) => { |
| 65 | + executeOrder.push(4); |
| 66 | + await next(); |
| 67 | + executeOrder.push(5); |
| 68 | + }; |
| 69 | + // Act |
| 70 | + const execute = compose<any>([mid1, mid2.handle.bind(mid2), mid3]); |
| 71 | + await execute({}); |
| 72 | + // Assert |
| 73 | + expect(executeOrder).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); |
| 74 | + }); |
| 75 | +}); |
0 commit comments