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?
Currently I have two ideas (both using 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'));
});
});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With