mardi 7 mars 2017

How can I test a normal plain javascript file?

If I have a plain javascript file

// hello.js
function hello(string) {
  return 'hello ' + string;
}

How can I use unit test over the functions in this file?

EDIT

Currently I have two ideas (both using nodejs):

eval + mochajs/nodejs

Test with mochajs test framework, for this I need use eval

// test file
var assert = require('assert');
var fs = require('fs');
eval.apply(this, [fs.readFileSync('./hello.js').toString()]);

describe('hello function', function() {
  it('test output', function () {
    assert.equal('hello world', hello('world'));
  });
});

automatically pre-convert the javascript file in a nodejs module

Before to run the test create automatically a copy of hello.js with the structure of a nodejs module and run the test over the copy

// _hello.js to testing
exports.hello = function(string) {
  return 'hello ' + string;
}

// test file
var assert = require('assert');
var hello = require('./_hello.js');

describe('hello function', function() {
  it('test output', function () {
    assert.equal('hello world', hello.hello('world'));
  });
});

In the second option, I need to make a script to convert the javascript file into a nodejs module, but I get some things like, in a nodejs module I can get the coverage measure.

Aucun commentaire:

Enregistrer un commentaire