Skip to content

Response Handler

Testing response handlers can be achieved by simply instantiating the response handler and calling the handle method.

Note

Because the response handler does not return a value but instead set it to the ctx.body, you need to test the values against the koa context.

demo-http/tests/response-handler.test.ts
import 'reflect-metadata';
import type { RouterContext } from '@koa/router';
import { RestResponseHandler } from '../src/response-handlers/rest.js';

test('Response is wrapped in data', async () => {
  const context = {
    body: undefined
  } as RouterContext;

  const fakeResponse = {
    username: 'hello'
  };

  const rh = new RestResponseHandler();

  await rh.handle(fakeResponse, {
    attachMeta: false
  }, context);

  expect(context.body).toStrictEqual({ data: fakeResponse, meta: undefined });
});
demo-http/src/response-handlers/rest.ts
import { RouterContext } from '@koa/router';
import type { ResponseHandlerInterface } from '@triptyk/nfw-http';
import { Ctx, Args } from '@triptyk/nfw-http';

export class RestResponseHandler implements ResponseHandlerInterface {
  public handle (lastResult: unknown, @Args() options: {
    attachMeta?: boolean,
  } | undefined, @Ctx() ctx: RouterContext): void | Promise<void> {
    ctx.body = {
      meta: options?.attachMeta ? 'meta' : undefined,
      data: lastResult
    };
  }
}