用玩笑测试Firebase功能

时间:2020-03-23 22:50:48

标签: typescript firebase jestjs google-cloud-functions

自两天以来,我一直在尝试理解并编写针对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模块?

1 个答案:

答案 0 :(得分:0)

我找到的解决方案非常简单而且不错。可以通过调用函数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');
    });
});