vendredi 27 mai 2016

How can I unit test a complex promise chain?

I have some JavaScript code:

var findLeastUsedPassage;

findLeastUsedPassage = function(StudentId) {
  var passageCounts;
  passageCounts = [];
  return db.Passage.findAll({
    where: {
      active: true
    }
  }).each(function(dbPassage) {
    var passage;
    passage = dbPassage.get();
    passage.count = 0;
    return passageCounts.push(passage);
  }).then(function() {
    return db.Workbook.findAll({
      where: {
        SubjectId: 1,
        gradedAt: {
          $ne: null
        },
        StudentId: StudentId
      },
      include: [
        {
          model: db.WorkbookQuestion,
          include: [db.Question]
        }
      ],
      limit: 10,
      order: [['gradedAt', 'DESC']]
    });
  }).each(function(dbWorkbook) {
    return Promise.resolve(dbWorkbook.WorkbookQuestions).each(function(dbWorkbookQuestion) {
      var passageIndex;
      passageIndex = _.findIndex(passageCounts, function(passageCount) {
        return passageCount.id === dbWorkbookQuestion.Question.PassageId;
      });
      if (passageIndex !== -1) {
        return passageCounts[passageIndex].count++;
      }
    });
  }).then(function() {
    passageCounts = _.sortBy(passageCounts, 'count');
    return passageCounts;
  });
};

and I want to unit test it (I think). I instrumented mocha to do the testing, but my test doesn't seem all that.. thorough:

describe('Finding the least used Passage', function() {
  it('should have a function called findLeastUsedPassage', function() {
    return expect(WorkbookLib.findLeastUsedPassage).to.exist;
  });
  return it('should return the least used passages for a student', function() {
    return WorkbookLib.findLeastUsedPassage(10).then(function(passageCounts) {
      var passageCountsLength;
      passageCountsLength = passageCounts.length;
      expect(passageCountsLength).to.equal(74);
      expect(passageCounts[0].count).to.be.at.most(passageCounts[1].count);
      expect(passageCounts[1].count).to.be.at.most(passageCounts[5].count);
      expect(passageCounts[56].count).to.be.at.most(passageCounts[70].count);
      return expect(passageCounts[70].count).to.be.at.most(passageCounts[73].count);
    });
  });
});

What's the right approach to unit testing something like this?

Aucun commentaire:

Enregistrer un commentaire