1

I am using firebase admin and I am trying to write some unit tests for my code.

Since admin is injected in my function I figured I could mock a very simple object like this:

admin = { 
  get auth () {
    return {
      updateUser: () => {
        return true;
      },
      createUser: () => {
        return true;
      },
      getUser: () => {
        throw Error('no user');
      }
    };
  }
};

Then in a particular test I can stub the functions. Here is what I have done so far:

// stubbed functions
sinon.stub(admin, 'auth').get(() => () => ({
  updateUser: () => ({ called: true }),
  getUser: () => (userRecord),
  createUser: () => ({ called: false })
}));

and those are working fine (I can see with my logs).

However in my test I would also want to check if createUser has been called at all. I thought I could set up a spy on the createUser function, but so far I can't really get it to work.

Here is what I have been trying (with a bunch of variation always failing):

it.only('should update a user', async () => {
  const userRecord = mockData

  sinon.stub(admin, 'auth').get(() => () => ({
    updateUser: () => ({ called: true }),
    getUser: () => (userRecord),
    createUser: () => ({ called: false })
  }));
  const spy = sinon.spy(admin, 'auth', ['get']); // this is not working

  const user = await upsertUser(data, firestore, admin);
  expect(user).toEqual(data.userDataForAuth); // this one is ok
  sinon.assert.calledOnce(spy.get); // this throws an error
});

the bit of code I am trying to test (which is the upsert function is this:

  // in my test exisiting user is not null (the stub `getUser` is returning a object
  if (existingUser != null) {
    try {
      await admin.auth().updateUser(uid, userDataForAuth);
      return userDataForAuth;
    } catch (error) {
      console.log('error', error);
      throw Error('error updating user');
    }
  }

I am not even sure this is the best approach, happy to change it if there is a better one!

mikey
  • 1,339
  • 5
  • 22
  • 43

0 Answers0