import { expect } from '../../test'; import { GraphqlOperation, GraphqlMiddlewareHandler } from '..'; import * as test from '../test'; const { query } = test.data; const mock = (callback?: test.MockCallback) => test.mock(test.data.QUERY_DATA, callback); describe('graphql: middleware', () => { it('from middleware client options', async () => { let op: GraphqlOperation | undefined; const client = test.client({ headers: { foo: 'bar', auth: 123456, 'my-func': operation => { op = operation; return 'calculated-result'; }, }, }); let headers: any; mock(args => { headers = args.headers; }); await client.query({ query }); expect(headers.auth).to.eql(['123456']); expect(headers.foo).to.eql(['bar']); expect(headers['my-func']).to.eql(['calculated-result']); expect(op && op.operationName).to.equal('AllFilms'); }); it('single middleware handler', async () => { let total = 0; const middleware: GraphqlMiddlewareHandler = (operation, next) => { total += 1; return next ? next(operation) : null; }; mock(); await test.client({ middleware }).query({ query }); expect(total).to.eql(1); }); it('two middleware handlers in sequential order', async () => { const order: string[] = []; const middleware: GraphqlMiddlewareHandler[] = [ (operation, next) => { order.push('first'); return next ? next(operation) : null; }, (operation, next) => { order.push('second'); return next ? next(operation) : null; }, ]; mock(); await test.client({ middleware }).query({ query }); expect(order).to.eql(['first', 'second']); }); });