unit-testing - 检查是否已使用 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');
}
}
我什至不确定这是最好的方法,如果有更好的方法,我很乐意改变它!
解决方案
推荐阅读
- java - Idea Intellij:Ubuntu 和 Maven:未找到 Idea 依赖项错误
- javascript - 与树中的匿名组件反应差异
- python - 获取图中唯一状态的数量
- sql - 合并两个表并按比例交错两个表的选择查询结果
- postgresql - 在PostgreSQL中创建表时指定列时,“meta jsonb”是什么意思?
- javascript - 无法访问 JS 数组中的字段
- flutter - 将 TextField 小部件用作子项时,工具提示不可见
- python-3.x - 是否可以在 Tkinter 中重用小部件?如果是这样,我该如何使用类来做到这一点?
- mysql - SELECT from sql 2 cols in 1 table group by date
- django - X没有属性'object' - Django