I have the following setup
firebase.client.ts
import * as config from 'config';
import * as firebase from 'firebase-admin';
/**
* Abstracts the initialization and direct use of Firebase.
*/
export class FirebaseClient {
static initialized = false;
static initialize() {
if (!FirebaseClient.initialized) {
const firebaseConfig: any = config.get('firebase');
firebase.initializeApp({
credential: firebase.credential.cert(JSON.parse(firebaseConfig.privateKey)),
databaseURL: firebaseConfig.databaseUrl,
});
FirebaseClient.initialized = true;
}
}
}
auth-preprocessors.ts
import * as firebase from 'firebase-admin';
import { Errors } from 'typescript-rest';
import { logger } from './logger';
import { Request } from 'express';
import { FirebaseClient } from './firebase.client';
/**
* @see https://firebase.google.com/docs/app-check/custom-resource-backend
* @param message
*/
export async function requireAppCheck(req: Request) {
FirebaseClient.initialize(); // Initialize FirebaseClient
doSomeStuff();
}
I have authentication.controller.ts
import { Inject } from 'typescript-ioc';
import { PATCH, Path, Preprocessor } from 'typescript-rest';
import { requireAppCheck } from '../utils/auth-preprocessors';
@Path('/')
@Security('apiKey')
export class AuthenticationController {
@Path('v1/path')
@PATCH
@Preprocessor(requireAppCheck)
public async myFunc(
): Promise<Response> {
return await doSomething();
}
}
And in authentication.controller.spec.ts
import * as AuthProcessors from '../utils/auth-preprocessors';
describe.only('PATCH /path', () => {
let requireAppCheckMock: jest.Mock;
beforeEach(() => {
requireAppCheckMock = jest.fn().mockResolvedValue('someValue');
jest.spyOn(AuthProcessors, 'requireAppCheck').mockImplementation(requireAppCheckMock);
});
it.only('does stuff', async () => {
const response = callController();
expect(response.status).toBe(200);
}
With this setup, I get the error below, which means that requireAppCheck is not being mocked correctly, and it uses the actual implementation (since it tries to call FirebaseClient.initialize
)
text: '{"status":500,"error":"Internal server error","stack":"SyntaxError: Unexpected end of JSON input\n at JSON.parse (<anonymous>)\n at Function.FirebaseClient.initialize (/path/to/firebase.client.ts:14:59)"}'*
I also tried doing
jest.mock('./../utils/auth-preprocessors', () => ({
requireAppCheck: requireAppCheckMock
}))
But I get the same result.