Skip to content

nshimiye/test-prep

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

test-prep

Run mocha programmatically

Step by Step

  • Create the test
// source: /test-prep/src/tests/t1.js
// nodejs = v6.9.4
'use strict';
var should = require('should');

var q1 = require('../questions/q1.js'); // q1 = question 1
var a1 = require('../answers/a1.js'); // a1 = answer 1

// @TODO fetch user input
var userInput = 3;

describe('Add', function() {
    it('should return value that same as [user input]', function() {
      a1().should.equal(userInput);
    });
});
  • Create a test runner
// source: /test-prep/src/runners/r1.js
// nodejs = v6.9.4
'use strict';
var Mocha = require('mocha');

var mocha = new Mocha({
  reporter: 'json'
});
mocha.addFile('<absolute-path>/test-prep/src/tests/t1.js');

/**
 * run the test and print 0 for failed test and 1 for passed
 * @returns Promise<{ status: string, score: number }>
 */
function main() {
  return new Promise(resolve => {

    mocha.run()
      .on('pass', function (test, success) {
        // I want to resolve the promise with the result generated by mocha:
        let status = 'Succeded', score = 1;
        return resolve({ status, score });
      })
      .on('fail', function (test, error) {
        // I want to resolve the promise with the result generated by mocha:
        let status = 'Failed', score = 0;
        return resolve({ status, score });
      });

  });
}
  • Run the test
// source: /test-prep/src/runners/r1.js
main().then(result => console.log(result));
node src/runners/r1.js

Releases

No releases published

Packages

No packages published