модульное тестирование задания cron node.js с подключением к БД - PullRequest
0 голосов
/ 17 марта 2020

Я могу запустить тестовый набор, но я столкнулся с проблемой с подключениями к БД в функции. Даже когда функция вызывается в тестовом наборе, код не покрывается. Я думаю, что заявления с ожиданием являются проблемой. Я попытался удалить ожидание, но это не имело никакого значения. у меня есть следующий код: app.js:

const server = (module.exports = {
    cronJob: null,
    scheduledJob: function() {
        server.cronJob= cron.schedule('*/30 * * * * *', async () => {
    // await DB.Get();
     await DB.Get();
    let alerts = Alerts.find({"muteStatus": false});
    let ts, fts, tts, per_dur, _id;
    var threshold_dur, time, triggerTime, medium;
    for ( let alert of alerts ) {
        if(alert.window !== 'currentDay') continue;
        _id = alert._id;
        threshold_dur = alert.threshold;
        ts = moment();
        tts = moment(ts).valueOf();
        fts = ts.subtract(threshold_dur, "minutes").valueOf();
        switch(alert.criteria) {
            case 'M-S':
                {
                    if (alert.notifications.level1.isNotified === true) { 
                        let asset = await Assets.findOne({ "assetId": alert.asset });   
                        let deviceId = asset.devices[0].devId;
                        let filter = { "mts":  { $gt: fts, $lte: tts }, "fst": { $in: [0,1,2,3] }, "tst": { $in: [0,1,2,3] }, "did": { $in: [, "99999031","99999032","99999044","99999045"] } };
                        let no_of_events = await Events.find(filter).countDocuments();
                        console.log(no_of_events);
                        console.log(threshold_dur);
                        if ( 6 >= threshold_dur ) {
                            //Send Mail
                            let users = await Users.find({ "unique_key": { $in : [alert.notifications.level1.userId[0], 
                                                                                    alert.notifications.level1.userId[1],
                                                                                    alert.notifications.level1.userId[2]]} });
                            for ( let user of users ) {
                                triggerTime = moment();
                                let email = user.email? user.email: '';
                                let phone = user.phone;
                                let full_name = user.firstName + user.lastName;
                                let alertMaker = await Users.findOne({ "unique_key": alert.userId });
                                let message = "Dear " + full_name + ", Notification for the alert defined by " + alertMaker.firstName + " " + alertMaker.lastName + ". Your asset " + alert.asset + " is IDLE for the last " + threshold_dur + " mins.";
                                if( alert.notifications.mode[0] ) {
                                    let desc = "Idle longer than " + threshold_dur + " mins.";
                                    let eventDefinedBy =  alertMaker.firstName + " " + alertMaker.lastName;
                                    let email_body = {
                                        subject: "Threshold Criteria met", assetId: alert.asset, time: triggerTime, description: desc, escLevel: 1, eventDefinedBy: eventDefinedBy
                                    }
                                    await EventsTriggered.create({ assetId: alert.asset ,time: triggerTime, address: alert.notifications.mode[0] === 'SMS'? phone: email, mode: alert.notifications.mode[0], escLevel: 1, message: message});
                                    await sendMail('idleLongerThan', email , email_body);
                                    let notifParam;
                                    notifParam = {
                                        "timestamp": triggerTime,
                                        "asset": alert.asset
                                    }
                                    send_notification(notifParam);
                                }
                                if(alert.notifications.mode[1]) {
                                    await EventsTriggered.create({ assetId: alert.asset ,time: triggerTime, address: alert.notifications.mode[0] === 'SMS'? phone: email, mode: alert.notifications.mode[1], escLevel: 1, message: message});
                                    let notifParam;
                                    notifParam = {
                                        "timestamp": triggerTime,
                                        "asset": alert.asset
                                    }
                                    send_notification(notifParam);
                                }
                            }
                            await Alerts.updateOne({ "_id": ObjectId(_id) }, { $set: { "notifications.level1.isNotified": true, "notifications.level1.notifiedTs": moment() } });
                        } else {
                            await Alerts.updateOne({ "_id": ObjectId(_id) }, { $set: { "notifications.level1.isNotified": false, 
                                                                                        "notifications.level2.isNotified": false,
                                                                                        "notifications.level3.isNotified": false } });
                        }
                    } else if (alert.notifications.level2.userId[0] !== '0' && alert.notifications.level2.isNotified === false) {
                        time = alert.threshold + alert.notifications.per_dur;
                        // per_dur = alert.notifications.per_dur;
                        ts = moment();
                        tts = moment(ts).valueOf();
                        fts = ts.subtract(time, "minutes").valueOf();
                        let filter = { "mts":  { $gt: fts, $lte: tts }, "fst": 0, "tst": 0 };
                        let no_of_events = await Events.find(filter).countDocuments();
                        if ( no_of_events >= time ) {
                            //Send Mail
                            if( (alert.notifications.level2.userId[0] !== null) && (alert.notifications.level2.userId[0] !== '') ) {
                                triggerTime = moment();
                                let user = await Users.findOne({ "unique_key": alert.notifications.level2.userId[0] });
                                let alertMaker = await Users.findOne({ "unique_key": alert.userId });
                                let email = user && user.email? user.email: '';
                                let phone = user? user.phone: '';
                                let full_name = user? user.firstName + user.lastName : '';
                                let message = "Dear " + full_name + ", Notification for the alert defined by " + alertMaker.firstName + " " + alertMaker.lastName + ". Your asset " + alert.asset + " is IDLE for the last " + time + " mins.";
                                if( alert.notifications.mode[0] ) {
                                    await EventsTriggered.create({ assetId: alert.asset ,time: triggerTime, address: alert.notifications.mode[0] === 'SMS'? phone: email, mode: alert.notifications.mode[0], escLevel: 2, message: message});
                                    let notifParam;
                                    notifParam = {
                                        "timestamp": triggerTime,
                                        "asset": alert.asset
                                    }
                                    send_notification(notifParam);
                                }
                                if(alert.notifications.mode[1]) {
                                    await EventsTriggered.create({ assetId: alert.asset ,time: triggerTime, address: alert.notifications.mode[0] === 'SMS'? 'SMS': 'E-Mail', mode: alert.notifications.mode[1], escLevel: 2, message: message});
                                    let notifParam;
                                    notifParam = {
                                        "timestamp": triggerTime,
                                        "asset": alert.asset
                                    }
                                    send_notification(notifParam);
                                }
                                await Alerts.updateOne({ "_id": ObjectId(_id) }, { $set: { "notifications.level2.isNotified": true, "notifications.level2.notifiedTs": moment() } });

                            }
                        } else {
                            await Alerts.updateOne({ "_id": ObjectId(_id) }, { $set: { "notifications.level1.isNotified": false, 
                                                                                        "notifications.level2.isNotified": false,
                                                                                        "notifications.level3.isNotified": false } });
                        }
                    } else if( alert.notifications.level3.userId[0] !== '0' && alert.notifications.level3.isNotified === false ) {
                        console.log("Inside level 3");
                        time = alert.threshold + alert.notifications.per_dur + alert.notifications.per_dur;
                        // per_dur = alert.notifications.per_dur;
                        ts = moment();
                        tts = moment(ts).valueOf();
                        fts = ts.subtract(time, "minutes").valueOf();
                        let filter = { "mts":  { $gt: fts, $lte: tts }, "fst": 0, "tst":0 };
                        let no_of_events = await Events.find(filter).countDocuments();
                        if ( no_of_events >= time ) {
                            //Send Mail
                            triggerTime =moment();
                            let user = await Users.findOne({ "unique_key": alert.notifications.level3.userId[0] });
                            let alertMaker = await Users.findOne({ "unique_key": alert.userId });
                            let email = user && user.email? user.email: '';
                            let phone = user? user.phone: '';
                            let full_name = user? user.firstName + user.lastName : '';
                            let message = "Dear " + full_name + ", Notification for the alert defined by " + alertMaker.firstName + " " + alertMaker.lastName + ". Your asset " + alert.asset + " is IDLE for the last " + time + " mins.";
                            if( alert.notifications.mode[0] ) {
                                await EventsTriggered.create({ assetId: alert.asset ,time: triggerTime, address: alert.notifications.mode[0] === 'SMS'? phone: email, mode: alert.notifications.mode[0], escLevel: 3, message: message});
                                let notifParam;
                                notifParam = {
                                    "timestamp": triggerTime,
                                    "asset": alert.asset
                                }
                                send_notification(notifParam);
                            }
                            if(alert.notifications.mode[1]) {
                                await EventsTriggered.create({ assetId: alert.asset ,time: triggerTime, address: alert.notifications.mode[0] === 'SMS'? phone: email, mode: alert.notifications.mode[1], escLevel: 3, message: message});
                                let notifParam;
                                notifParam = {
                                    "timestamp": triggerTime,
                                    "asset": alert.asset
                                }
                                send_notification(notifParam);
                            }
                            await Alerts.updateOne({ "_id": ObjectId(_id) }, { $set: { "notifications.level3.isNotified": true, "notifications.level3.notifiedTs": moment() } });
                            } else {
                            await Alerts.updateOne({ "_id": ObjectId(_id) }, { $set: { "notifications.level1.isNotified": false, 
                                                                                        "notifications.level2.isNotified": false,
                                                                                        "notifications.level3.isNotified": false } });
                        }
                    }
                    break;
                }
        }
    }
    });
  },
  run: function() {
    console.log("run called");
  },
});

Ниже приведен файл моего набора тестов: app.spec.js

  afterEach(async () => {
    sinon.restore();
  });
  describe("#scheduledJob", async () => {
    it("should schedule job", async () => {
      const pattern = "* * * * * *";
      const runStub = sinon.stub(server, "run");
      const scheduleStub = await sinon
        .stub(cron, "schedule")
        .yields()
        .returns({});
      await server.scheduledJob();
      expect(server.cronJob).to.be.eql({});
    });
  });
});
```[code is not getting covered][1]


  [1]: https://i.stack.imgur.com/OEZWW.png
...