用jest测试firebase函数



两天以来,我一直在努力理解并编写firebase函数的测试。对于那个测试,我只想使用框架Jest。https://jestjs.io/

export const updateTipsPerFixture = functions.firestore.document('users/{userId}').onUpdate((change) => {
const beforeTips: Tip[] = change.before.data() !== undefined ? change.before.data().tips : [];
const afterTips: Tip[] = change.after.data() !== undefined ? change.after.data().tips : [];
if (JSON.stringify(beforeTips) === JSON.stringify(afterTips)) {
return new Promise(resolve => resolve('equal'));
}
if (afterTips.length === beforeTips.length) {
return new Promise(resolve => resolve('same length'));
}
if (beforeTips.length < afterTips.length) {
return new Promise(resolve => resolve('afterTips.length is longer'));
}
return false;
});

即使在我阅读了Jest文档之后,我也不知道如何为我的用例模拟/存根firebase函数模块。

这是我来的地方。是的,不远。

describe('updateTipsPerFixture', () => {
test('it should return true when tips are equal', () => {
expect(updateTipsPerFixture).toEqual(new Promise(resolve => 'equal'));
});
});

我应该如何编写测试和模拟firebase模块?

我找到的解决方案非常简单和好。可以通过调用函数run((并传递一些数据来测试该函数。参见示例:

describe('updateTipsPerFixture', () => {
test('it should return true when tips are equal', () => {
const mockedData = {
before: {
data(): FirebaseFirestore.DocumentData | undefined {
return {tips: [{fixtureId: 123, teamId: 123} as Tip]}
}
},
after: {
data(): FirebaseFirestore.DocumentData | undefined {
return {tips: [{fixtureId: 123, teamId: 123} as Tip]}
}
}
} as Change<DocumentSnapshot>;
const actual = updateTipsPerFixture.run(mockedData, null);
return expect(actual).resolves.toEqual('equal');
});
});

相关内容

  • 没有找到相关文章

最新更新