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):
- How createAuthRoutes is mocked in the test... am I extending it correctly?
- Should I be mocking app.use() ?
- Is that the correct mock of passport?
I'm really stuck on this one and would really appreciate anyone's help!