dimanche 5 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

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'));
  });
});

Aucun commentaire:

Enregistrer un commentaire