middleware must be a function for koa passport testing using jest typescript

大兔子大兔子 提交于 2020-04-07 08:11:53

问题


Running into a few issues when trying to mock an oauth2 flow using passport and koa...

The error when running test:

  TypeError: middleware must be a function!

  26 |   app.use(bodyParser());
> 27 |   app.use(authRouting as any);
     |       ^

auth.ts:

import { KoaPassport } from 'koa-passport';
import * as Router from 'koa-router';

import { signAccessToken } from '../utils/jwt';

export function createAuthRoutes(passport: InstanceType<typeof KoaPassport>) {
  const router = new Router();

  router.get('/api/login', passport.authenticate('oauth2'));

  router.get('/api/authorize', passport.authenticate('oauth2'), (ctx: any) => {

    const {accessToken} = ctx.session.passport.user;

    const signedAccessToken = signAccessToken({accessToken});

    ctx.body = {token: signedAccessToken};
    ctx.status = 200;
  });

  return router;
}

Perhaps I'm not correctly constructing the exported function createAuthRoutes() in my test?

auth.spec.ts:

import { Server } from 'http';
import * as Koa from 'koa';
import * as bodyParser from 'koa-bodyparser';
import * as supertest from 'supertest';
import * as passport from 'passport';
import { createAuthRoutes } from './auth';

const mockedPassport = passport as jest.Mocked<typeof passport>;

const authRouting = createAuthRoutes(mockedPassport as any);


describe.only('Auth routes', () => {
  let server: Server;
  let request: supertest.SuperTest<supertest.Test>;
  let response: supertest.Response;

  const app = new Koa();

  app.use(bodyParser());
  app.use(authRouting as any);

  console.log('authRouting', authRouting);

  beforeAll(() => {
    server = app.listen();
    request = supertest(server);
  });

  afterAll(() => {
    server.close();
  });

  // it('should return a signed access token for authorize', async () => {});

});

A few areas I'm unsure of (that are probably to blame):

  1. How createAuthRoutes is mocked in the test... am I extending it correctly?
  2. Should I be mocking app.use() ?
  3. Is that the correct mock of passport?

I'm really stuck on this one and would really appreciate anyone's help!

来源:https://stackoverflow.com/questions/60914997/middleware-must-be-a-function-for-koa-passport-testing-using-jest-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!