首页 > 解决方案 > 检查是否已使用 sinon spy 调用了存根的 getter 函数

问题描述

我正在使用firebase admin并且正在尝试为我的代码编写一些单元测试。

由于admin被注入到我的函数中,我想我可以模拟一个非常简单的对象,如下所示:

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

然后在一个特定的测试中,我可以对函数进行存根。这是我到目前为止所做的:

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

并且那些工作正常(我可以通过我的日志看到)。

但是,在我的测试中,我还想检查是否createUser已经调用过。我以为我可以在该功能上设置一个间谍createUser,但到目前为止我还不能真正让它工作。

这是我一直在尝试的(一堆变化总是失败):

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
});

我正在尝试测试的代码位(upsert function就是这样:

  // 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');
    }
  }

我什至不确定这是最好的方法,如果有更好的方法,我很乐意改变它!

标签: unit-testingsinonspy

解决方案


推荐阅读