Reputation: 24764
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.
Upvotes: 9
Views: 17277
Reputation: 5954
For this you could use QUnit.
You would setup a test harness like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test Suite</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.10.1.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.10.1.js"></script>
<script src="hello.js"></script>
<script>
// This can of course be in a separate file
QUnit.test( "hello test", function( assert ) {
assert.ok( hello('world') === "hello world", "Passed!" );
});
</script>
</body>
</html>
Upvotes: 5
Reputation: 656
Use PreemJS, it's good for API\Unit javascript testing
"use strict";
let Preem = require('preem');
let preem = new Preem();
preem.testModule("Test hello function", function(beforeEach, checkIf) {
function hello(string) {
return 'hello ' + string;
}
let str = hello('world');
checkIf(str).isEqualTo('hello world', "strings are equal", "strings aren't equal");
}
preem.start();
Upvotes: 0
Reputation: 24764
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
Upvotes: 8
Reputation: 1102
1) go to https://jsfiddle.net/, 2) type in your code in Javascript block. 3) Open Chrome Console window by press F12 on Windows. 4) Click Run on left-top. hope this helps.
Upvotes: -4