对调用外部API的Firebase云功能进行单元测试的正确方法

时间:2018-10-05 07:06:46

标签: node.js firebase google-cloud-firestore google-cloud-functions

对调用外部API的Firebase云功能进行单元测试的正确方法。我的firebase云功能如下

const functions = require('firebase-functions');
var Analytics = require('analytics-node');
//fetching segment api key
var segmentKey = functions.config().segment.key;
var analytics = new Analytics(segmentKey);

/**
 * this gf will get called when document is added to 
 * app-open-track collection.
 */
exports.trackAppOpen = functions.firestore
  .document('app-open-track/{token}')
  .onCreate((snap, context) => {
    const snapValue = snap.data();
    const userId = snapValue.hasOwnProperty('userId') ? snapValue.userId : "";
    const deviceId = snapValue.hasOwnProperty('deviceId') ? snapValue.deviceId : "";
    const deviceType = snapValue.hasOwnProperty('deviceType') ? snapValue.deviceType : "";
    const osVersion = snapValue.hasOwnProperty('osVersion') ? snapValue.osVersion : "";
    const createdAt = snapValue.hasOwnProperty('createdAt') ? snapValue.createdAt : "";
    //checking user id exists if yes proceed
    if (!userId) {
      return false;
    } else {
      //sending data to segment API
      analytics.track({
        "type": "track",
        "userId": userId,
        "event": "app opened",
        "properties": {
          "deviceId": deviceId,
          "deviceType": deviceType,
          "osVersion": osVersion,
          "createdAt": createdAt
        }
      });
    }
    return true;
  });

我为此编写的测试用例是

const chai = require('chai');
const assert = chai.assert;
const test = require('firebase-functions-test')();
test.mockConfig({ segment: { key: 'MEhxCjq9YcWTRHLa7y2ArYHEugmRJUV0' } });
const trackOpenTestFunctions = require('../index.js');
describe('trackAppOpenCase', () => {
    it('valid request parameters -this should send data to segment API and return true', () => {
        // Make snapshot
        const snap = test.firestore.makeDocumentSnapshot({ deviceId: '456754765', osVersion: '12.3', userId: '0000007' }, 'app-open-track/{token}');
        // Call wrapped function with the snapshot
        const wrapped = test.wrap(trackOpenTestFunctions.trackAppOpen);
        wrapped(snap);
        return assert.equal(wrapped(snap), true);
    });

    it('removing userId key from request - this should not send data to segment API and return false', () => {
        // Make snapshot
        const snap = test.firestore.makeDocumentSnapshot({ deviceId: '456754765', osVersion: '12.3' }, 'app-open-track/{token}');
        // Call wrapped function with the snapshot
        const wrapped = test.wrap(trackOpenTestFunctions.trackAppOpen);
        wrapped(snap);
        return assert.equal(wrapped(snap), false);
    });

});

问题在于测试不是在等待api完成,什么是测试这种情况的最佳方法,我是否需要更改代码以便可以对其进行更好的测试。

0 个答案:

没有答案