firebase-functions-test icon indicating copy to clipboard operation
firebase-functions-test copied to clipboard

Wrapped Cloud Function creating data in wrong environment

Open beardo01 opened this issue 4 years ago • 1 comments

Version info

firebase-functions-test: 0.2.1

firebase-functions: 3.6.2

firebase-admin: 8.12.1

Test case

Function

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

export const onUserCreation = functions.auth.user().onCreate(async (user) => {
    const newUserDoc = {
      email: "email"
    }

    await admin.firestore().collection('users').add(newUserDoc);
});

Test Case

import { testEnv, testFirestore } from '../../../admin';
import { onUserCreation } from '../onUserCreation';
import { WrappedFunction } from 'firebase-functions-test/lib/main';

describe('onUserCreation Tests', () => {
  let testTarget: WrappedFunction;

  beforeEach(() => {
    testTarget = testEnv.wrap(onUserCreation);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  afterAll(() => {
    testEnv.cleanup();
  });


  it('should create a new user document in users collection', async () => {
    // Setup
    const userRecord = testEnv.auth.exampleUserRecord();
    userRecord.email = 'email';

    // Execute
    await testTarget(userRecord);

    // Verify
    const afterUserDoc = await testFirestore
      .collection('users')
      .where('email', '==', 'email')
      .get();

    expect(afterUserDoc.docs.length).toEqual(1);
  });
});

Steps to reproduce

import serviceAccount from '../service-account-prod.json';
import serviceAccountDev from '../service-account-dev.json';
import functions from 'firebase-functions-test';
import * as admin from 'firebase-admin';

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount as any),
  databaseURL: PRODUCTION_DATABASE_URL
});

const devApp = admin.initializeApp(
  {
    credential: admin.credential.cert(serviceAccountDev as any),
    databaseURL: DEV_DATABASE_URL
  },
  DEV_ENVIRONMENT_NAME
);

export const auth = admin.auth();
export const firestore = admin.firestore();
export const firestoreNS = admin.firestore;
export const testFirestore = devApp.firestore();

const projectConfig = {
  projectId: DEV_PROJECT_ID
  databaseURL: DEV_DATABASE_URL
};
export const testEnv = functions(projectConfig, '../service-account-dev.json');

Expected behavior

Since the onUserCreation Cloud Function is being wrapped by testEnv.wrap in the beforeEach part of the test, the onUserCreation should be creating the user document in the devApp.

Actual behavior

When testTarget is called the WrappedFunction is creating the user document in the production environment instead of the testing environment.

beardo01 avatar Jun 08 '20 10:06 beardo01

@beardo01 Hi did you manage to solve this problem? I was also facing the same issue but cannot find solution elsewhere.

sengasdf avatar Sep 23 '22 08:09 sengasdf