How to call Firebase HTTPS Callable Functions while writing Integration Tests using @firebase/testing?

Viewed 358

I am trying to write integration tests for my code. I want to use Firebase Local Emulator to be able to test end to end and see if documents and collections are being updated properly. I wrote a sample trigger for the sake of understanding how the emulator works

exports.myItemAdder = functions.https.onCall(async (data, context) => {
  if(!context.auth){
    throw new functions.https.HttpsError('unauthenticated', 'Sign in');
  }
  
  try{
    await db.doc('test-items/test-item').set({
      name: data.name,
      description: 'Learning to write Integration Tests'
    });
  }
  catch(error){
    throw new functions.https.HttpsError('unknown', error);
  }

  return 'Document Added'
});

This is how my test looks

describe('Calling myItemAdder adds another document', () => {
  const db = firebase.initializeTestApp({ projectId: REAL_FIREBASE_PROJECT_ID, auth: aliceAuth }).firestore();
  
  const functions = firebase.initializeTestApp({ projectId: REAL_FIREBASE_PROJECT_ID }).functions();
  functions.useFunctionsEmulator("localhost:5001");
  let myItemAdderFunc = functions.httpsCallable('myItemAdder')

  after(() => {
    firebase.clearFirestoreData({projectId: REAL_FIREBASE_PROJECT_ID});
  });

  it('Should return document added', async() => {
    const result = await myItemAdderFunc({'name': 'Test'});
    expect(result.data).to.equal('1Document Added');  // This should fail
  });
});

But when I run the test using npm test command, it gives me this error

Error: internal
      at new HttpsErrorImpl (node_modules/@firebase/functions/dist/index.node.cjs.js:59:28)
      at _errorForResponse (node_modules/@firebase/functions/dist/index.node.cjs.js:154:12)
      at Service.<anonymous> (node_modules/@firebase/functions/dist/index.node.cjs.js:539:33)
      at step (node_modules/@firebase/functions/node_modules/tslib/tslib.js:136:27)
      at Object.next (node_modules/@firebase/functions/node_modules/tslib/tslib.js:117:57)
      at fulfilled (node_modules/@firebase/functions/node_modules/tslib/tslib.js:107:62)

When I call this function using firebase functions:shell it runs perfectly and adds the document to the emulated version of Firestore

0 Answers
Related