1
votes

I have a lot of middleware. Here is one of them. How can I test my middleware with type compliance and with context.state validation on typescript ?


async function internationalizationPlugin(
  context: ParameterizedContext<AppState, AppContext>,
  next: Next
) {
  context.state.i18n = await (i18next as any).createInstance({
    lng: context.state.language,
    fallbackLng: 'en',
  })
  await next()
}
2

2 Answers

0
votes

a linter will check for type compliances and will be able to customize them more. However, you would just need to make sure that you export the function to your test file and then run a expect(typeof context).to.be(ParameterizedContext<AppState, AppContext>) that's not 100% copy/pasteable code, but, I think that it is on the right track. Also, for testability it could be easier if you created a class out of your middlewares that way importing and testing are done easier.

0
votes

It's my simple type support solution. I'm not sure if it is suitable for everyone.

import * as httpMocks from 'node-mocks-http'
import * as Koa from 'koa'

export interface MockContext<RequestBody = undefined> extends Koa.Context {
  request: Koa.Context['request'] & {
    body?: RequestBody
  }
}

export const koaMockContext = <
  State = Koa.DefaultState,
  Context = MockContext,
  RequestBody = undefined
>(
  requestBody?: RequestBody
) => {
  const req = httpMocks.createRequest()
  const res = httpMocks.createResponse()
  const app = new Koa<State, Context>()
  const context = app.createContext(req, res) as MockContext<RequestBody> & Koa.ParameterizedContext<State, Context>
  res.statusCode = 404
  context.request.body = requestBody
  return context
}

And example

import { AppContext, AppState } from './types'
import { koaMockContext } from './utils'
import { internationalizationPlugin } from '../src/internationalizationPlugin'

describe('internationalizationPlugin', () => {
  const ctx = koaMockContext<AppState, AppContext>()

  it('should not be undefined', async () => {
    await internationalizationPlugin(ctx, async () => {})
    expect(ctx.state.i18n).not.toBe(undefined)
  })
})