Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
JuanPablo Avatar asked May 22 '26 16:05

JuanPablo


1 Answers

Finally I solved with karma + phantomjs + jasmine

with karma I can load the javacript file and tests files adding lines to the karma configuration file this way

// karma.conf.js
files: [
  'hello.js',
  'hello_test.js'
],

and write the tests this way

// test_hello.js
describe('test lib', function () {
  it('test hello', function () {
    expect(hello('world')).toBe('hello world');
  });
});

A example available in github

https://github.com/juanpabloaj/karma_phantomjs_jasmine

like image 70
JuanPablo Avatar answered May 25 '26 06:05

JuanPablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!