I'm using firebase-admin to authenticate requests made to my express server. I'm looking to write unit tests for my routes, but I'm blocked on testing routes that require authentication.
I have a middleware that checks if requests are authenticated.
public resolve(): (req, res, next) => void {
return async (req, res, next) => {
const header = req.header('Authorization');
if (!header || !header.split(' ')) {
throw new HttpException('Unauthorized', UNAUTHORIZED);
}
const token = header.split(' ')[1];
await admin.auth().verifyIdToken(token).then((decodedToken: any) => {
req.user = decodedToken;
next();
}).catch((error: any) => {
throw new HttpException(error, UNAUTHORIZED);
});
};
}
So far, I can only unit test my routes to make sure that they respond UNAUTHORIZED instead of NOT_FOUND.
it('GET /api/menu should return 401 ', done => {
const NOT_FOUND = 404;
const UNAUTHORIZED = 401;
supertest(instance)
.get('/api/menu')
.end((error, response: superagent.Response) => {
expect(response.status).not.toEqual(NOT_FOUND);
expect(response.status).toEqual(UNAUTHORIZED);
done();
});
});
But, I want to write more unit tests than this! I'd like a way to mock an authenticated user. Perhaps I'm overcomplicating this and don't need a feature from firebase-admin, but I thought I might as well ask.
Could there be a feature to mock the ID token of test users in my firebase db so that I can unit test my routes with users of different types?
I've asked about how this might be possible currently on stack overflow here. Sorry if I'm over complicating this, but this might be a pretty nifty feature if not possible already.
I think you already have a couple of options here:
admin.auth().createCustomToken()), and then exchange it for an ID token using the Firebase client SDK. We do this in our integration tests.The first approach requires a service account with a private key. Second approach requires making RPC calls, so your test environment should have network connectivity.
@CoreyCole You can try out this library which I maintain: https://github.com/soumak77/firebase-mock
It supports all your needs for mocking your use case including authentication, firebase http functions, tokens, and more
@hiranya911 For approach number one, are you just using the jsonwebtoken NPM module to sign your own custom token based on the parameters that the Firebase Admin SDK expects?
After generating that custom token, would it be correct to say that passing it into the Admin SDK for Node to verify the token would come back verified and the auth middleware would consider the request authenticated, or, does the Firebase Node Admin SDK have to be mocked?
Thanks.
I am facing same issue. Does anyone find solution of this question?
Most helpful comment
@CoreyCole You can try out this library which I maintain: https://github.com/soumak77/firebase-mock
It supports all your needs for mocking your use case including authentication, firebase http functions, tokens, and more