JavaScript Libraries Spilled EVERYWHERE! Series #002

In the last blog entry I wrote up vows.js for testing JavaScript, in this I’ve tried out another testing framework called mocha. This framework is pretty extensive as you can do the things you do with vows.js as well as a lot of other techniques. In addition to mocha I’ve added a few other things to the mix. As well as a few obvious points where I need to RTFM still about how mocha works.

mocha.js

Before falling off into a conversation about reading the manual, I’ll dive into a bit about mocha. Mocha is a project, hosted on github as you might expect, that aims to provide a very feature rich test framework that can run via node or the browser. It also enables asynchronous and synchronous testing with some pretty sweet reporting.

The installation is the standard simplicity of a beautiful and elegant package from npm for node.js.

[sourcecode language=”bash”]
$ npm install -g mocha
[/sourcecode]

Of course, depending on the way you’ve setup your machine, you may need to hit that command with sudo. The sample test on the main documentation & project page is pretty straight forward, I’ve copied it below for easy reference.

[sourcecode language=”bash”]
$ npm install -g mocha
$ mkdir test
$ $EDITOR test/test.js
[/sourcecode]

Note that above, where “$EDITOR” is whatever editor you’re using, such as Sublime 2, Textmate, Webstorm or whatever.

[sourcecode language=”javascript”]
var assert = require("assert")
describe(‘Array’, function(){
describe(‘#indexOf()’, function(){
it(‘should return -1 when the value is not present’, function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
[/sourcecode]

Then run the test.

[sourcecode language=”bash”]
$ mocha

.

✔ 1 test complete (1ms)
[/sourcecode]

Overall, pretty sweet and simple. There are ways to setup mocha to do TDD or BDD style also. What I’ve done for my basic name generator I’m building has started of super simple. One of the other additions that I’ve added below is the should.js library. I’ll add more about this library, and the intent behind using it in the next blog article I write up.

My first tests I’ve put together I’ve entered below.

[sourcecode language=”javascript”]
require(‘should’);
var factory = require(‘./../lib/NameFactory’).nameFactory;

describe(‘when working with names using NameFactory’, function(){
var generateThisManyNames = 3;

describe(‘generating names’, function(){
it(‘should return a name between 3 and 20 characters’, function(){
factory.generate_names().length.should.be.approximately(3,20);
});
it(‘should return correct number of names’, function(){
factory.generate_names(generateThisManyNames).length.should.equal(generateThisManyNames);
});
})
});
[/sourcecode]

…and then I’ve implemented the absolute basic to get those tests to pass. You JavaScripters that have been at it for a while can likely detect my massive newbism among this code. I’d love feedback btw. 🙂 So here’s my basic implementation so far.

[sourcecode language=”javascript”]
module.exports.nameFactory = {
generate_names: function (count) {
if (count > 1){
return [”,”,”];
}
else{
return ‘stuff’;
}
}
};
[/sourcecode]

I’m still sketch on best practices around a number of object uses and creation in JavaScript. For instance in my code above, I’m creating a module, and setting up properties with functions, which leads to a number of questions… (maybe it is stack overflow time)

  • Is this an efficient way to create a JavaScript function for returning randomly created names?
  • What would your first tests be when creating a name generator? Any suggestions on some tests to add?
  • This shows some of my intent, such as returning a single result if no count is entered or it is less than 2, any suggestions on doing a kind of overloaded factory pattern method like that?
  • Now that I’ve gotten what I do above, I need some more tests to add to confirm that the returned content isn’t [”,”,”] <- cuz’ obviously that’s useless and not random, just returns the 3 string array that would prospectively have generated (or randomly selected) names. Ideas?
  • Is there another way to create a class or namespace that isn’t “module.export…” like I have above with “module.exports.nameFactory”? I’d love to just have a “NameFactory” or something. Not sure how or what way would be best in JavaScript land to put something like that together.

I’ve already moved past just this, but would love any feedback on the above questions and code snippets. I’ll post my results and the changes and additions from any body that posts feedback and suggestions in a subsequent post.  🙂

Cheers!

Portlanders Going to Cascadia.js? Ride the “Geek Train to Cascadia”

We’ll be boarding Amtrak Cascades #508 to Seattle departing Portland at 6:15pm from Union Station. If you’re interested in doing a bulk ticket purchase let me know ASAP and I’ll work with you to organize that. Otherwise if you just want to pick up a ticket and meet us on the train let us know that too.

Logistics

Make sure to let me know if you want to join the riders & we’ll join up to be boarded together in the same car, this way we can get tables, seats and code together or at least have a good convo, a beer or three (or wine or juice or whatever you’d prefer) while sitting back, relaxing and enjoying the ride to Seattle.

So RSVP me here & we’ll get this moose LIT UP!

Coder’s Vacation : OMG! JavaScript Libraries Spilled EVERYWHERE! Series #001

NOTE: All parts of this series and my other series can be found on my series links page.

I sat down a few days ago on this trip to get a simple project setup, instead something else happened. It is my fault, entirely my fault. I could have stayed focused on a single library but instead I’ve let them explode. They’re everywhere now in my project!  😮  I’ve learned a great deal about breaking and fixing things though when working with testing frameworks and Node.js. All of this being rooted in my exceedingly simple project called NameFactory on Github. Here’s a few of the things I’ve stumbled through over the course of figuring out these testing frameworks.

vows.js (while chillin’ at Phils Coffee)

Phils Coffee, a staunch cup indeed!
Phils Coffee, a staunch cup indeed!

If you aren’t familiar with vows, here’s the brief description. Vows is a node.js testing framework that is built around the notion of BDD, Behavior Driven Development. The other important thing to note, is vows.js was built specifically to test asynchronous code. It can test others, but it is more oriented toward asynchronous code. Vows also runs tests in parallel, which thinking about that it takes the random order execution and ups the game even further by running them this way. It can really tighten up code execution and regression that things will indeed work in many different conditions. Building for web scale on the internet, that’s something we definitely need!  🙂

To install vows, it follows your standard pattern with npm:

[sourcecode language=”bash”]
npm install vows
[/sourcecode]

When I installed it I really bit the bullet and went for a global install.

[sourcecode language=”bash”]
sudo npm install -g vows
[/sourcecode]

From there I spun up a really simple example that is shown on the vows.js site:

[sourcecode language=”javascript”]
var vows = require(‘vows’),
assert = require(‘assert’);

vows.describe(‘Division by Zero’).addBatch({
‘when dividing a number by zero’: {
topic: function () { return 42 / 0 },

‘we get Infinity’: function (topic) {
assert.equal (topic, Infinity);
}
},
‘but when dividing zero by zero’: {
topic: function () { return 0 / 0 },

‘we get a value which’: {
‘is not a number’: function (topic) {
assert.isNaN (topic);
},
‘is not equal to itself’: function (topic) {
assert.notEqual (topic, topic);
}
}
}
}).run();
[/sourcecode]

From this example you run the tests by executing the code with the following command:

[sourcecode language=”bash”]
node division-by-zero-test.js
[/sourcecode]

This is all fine, but I’d rather be using the vows test runnner. To do that you’ll need to, instead of *.run(); call the *.export(); function instead. At this point I started scratching my head a bit and looking for parallels between my understanding of BDD and testing and what vows is doing. So I read further and came up with a few observations.

In vows the convention is to have one test suite per file and have the subject match the name. This makes sense to me, that’s how I’ve generally done similar things with Ruby, C# and the like. You end up with something like this for setting the subject and adding the various test suites:

[sourcecode language=”javascript”]
var suite = vows.describe(‘subject’);

suite.addBatch({/* run 1st */}).addBatch({/* 2nd */}).addBatch({/* 3rd */});

suite.addBatch({
‘A context’: {
topic: function () {/* Do something async */},
‘I am a vow’: function (topic) {
/* Test the result of this topic */
}
},
‘Another context’: {
topic: function () {/* Do something else async */},
‘I am another vow’: function (topic) {
/* Test the result of this topic */
},
‘I am another sub-context vow’: function (topic) {
/* Test the result of the topic */
},
‘And another sub-context’: {
/* Executed when the tests above finish running */
}
}
});
[/sourcecode]

Each of the topics are the thing that is being tested with the secondary element of each test being the test to verify the topic. Each of these things are run asynchronously, in parallel, so be sure to keep that in mind when using this framework. However note, in the sub-context tests above the sub-context happens in order. This can be used in various ways, but be sure to not abuse this execution model to avoid the asynchronous nature of JavaScript, I’ve only been working with vows for a few days and have already seen code snippets on the web that have done exactly that!

So this is the first part in a series where I’ll just cover all sorts of JavaScript libraries. It took a Coder’s Vacation however to get me started on this series, enjoy.

Coder’s Vacation : Getting Some Names…

Actual Live Status of the NameFactory Project

One of the things I’ve started working on is a #PhatData (re: my renamed version of big data) sample. So far what I’ve created is a JavaScript Application that works something like this. (The actual build status is shown to the right here in the “build status” image)

Step #1: Continuous Integration

The first thing I did was setup a solid node.js project that works on Travis CI (Continuous Integration). This is a pretty quick process. First create a directory and add an appropriate .gitignore and README.md file.

[sourcecode language=”bash”]
$ mkdir NameFactory
$ cd NameFactory/
$ git init
Initialized empty Git repository in /Users/adron/coderz/NameFactory/.git/
$ git remote add origin git@github.com:Adron/NameFactory.git
$ mate README.md
$ mate .gitignore
[/sourcecode]

The mate command is merely textmate, use whatever you’d like though to create the files. I also use Sublime 2 and other things, textmate just happens to be the poison I often choose from the command line. The .gitignore has the following to take care of WebStorm and other files that might pop up.

[sourcecode language=”bash”]
*.idea
.idea
idea
.DS_Store
*.DS_Store

lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz

pids
logs
results

node_modules
npm-debug.log
[/sourcecode]

The README.md I just put the following in. You don’t really need this, but I’m showing you what should be put in a minimal project. In addition to being a good practice, we’ll need the README.md file for plugging in Travis CI in a few steps.

[sourcecode language=”bash”]
Name Factory
===
Description: This is JavaScript Node.js Project for generating random names.
[/sourcecode]

Commit those files.

[sourcecode language=”bash”]
$ git add -A
$ git commit -m ‘Adding gitignore and README.md.’
[master (root-commit) 14b1cf8] Adding gitignore and README.md.
2 files changed, 23 insertions(+)
create mode 100644 .gitignore
create mode 100644 README.md
$
[/sourcecode]

Once that is added there are some other files needed for Travis CI that I’ll add before flipping on the actual CI project on the Travis CI Website. First add a .travis.yml file to the project.

[sourcecode language=”ruby”]
language: node_js

# test on two node.js versions: 0.6 and 0.8
node_js:
– 0.6
– 0.8
[/sourcecode]

The packages file should look like this.

[sourcecode language=”javascript”]
{
"author": "Adron Hall <adronhall@gmail.com>",
"name": "NameFactory",
"description": "A library that creates randomly generated names for insert into various databases.",
"version": "0.0.1",
"homepage": "https://github.com/Adron/NameFactory/wiki&quot;,
"main": "./lib/names",
"repository": {
"type": "git",
"url": "git@github.com:Adron/NameFactory.git"
},
"scripts": {
"test": "vows –spec"
},
"engines": {
"node": ">= 0.4"
},
"dependencies": {},
"devDependencies": {
"vows": "0.6.x"
}
}
[/sourcecode]

At this point add a few tests that you know pass. I added the following examples from the vows site (this is the default example on the site).

[sourcecode language=”javascript”]
var vows = require(‘vows’),
assert = require(‘assert’);

// Create a Test Suite
vows.describe(‘Division by Zero’).addBatch({
‘when dividing a number by zero’: {
topic: function () { return 42 / 0 },

‘we get Infinity’: function (topic) {
assert.equal (topic, Infinity);
}
},
‘but when dividing zero by zero’: {
topic: function () { return 0 / 0 },

‘we get a value which’: {
‘is not a number’: function (topic) {
assert.isNaN (topic);
},
‘is not equal to itself’: function (topic) {
assert.notEqual (topic, topic);
}
}
}
}).run();
[/sourcecode]

…now make sure the tests run ok…

[sourcecode language=”bash”]
$ node test/names_object_should_exist.js
··· ✓ OK » 3 honored (0.003s)
$
[/sourcecode]

So that’ll get the continuous integration via Travis-CI for NameFactory up and running, with a Github NameFactory Repository that is ready for the name generation code to be added. For my next blog entry I’ll leap into some generation strategies, dig up some good name lists (if you know of any, leave a comment w/ a link), and work on figuring out the fastest way to generate names.

Once that’s done, it’s time to setup some distributed databases.
Shout it

HTML, CSS, JavaScript and Metro App Building on Windows 8 Part 2

In the first part of this seriesI kicked everything off by starting a Windows 8 JavaScript Project and added QUnit-Metro via Nuget. Now that we have a small executable application, I’ll get some things added and cover what exactly it is we’re doing in each part. Open the project up that we created in the previous blog entry of the series. Once open find and open the default.html, default.js and default_tests.js files to work with. In the default.js file you’ll find the following code in the default.js.

[sourcecode language=”javascript”]
(function () {
"use strict";

var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();

app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
} else {
}
args.setPromise(WinJS.UI.processAll());
}
};

app.oncheckpoint = function (args) {
};

app.start();
})();
[/sourcecode]

A Bit of Context – default.js

At the beginning you’ll find that all the code is enclosed in a self-executing anonymous function. This gives us the ability to avoid naming conflicts or accidentally modifying variables in other spaces. Kind of the “namespaces” of C# or other organizational code features from other languages (I said kind of, there are other ways to do this too, this is just one). The other cool thing about this is it keeps identifiers out of the global namespace which also helps performance (it’ll also get you called all sorts of stuff if you create global variables in JavaScript! I’m nice, I won’t do it, but be prepared to be appropriately punished for such dissension as global variable creation! I warned ya.).

This next part (reminds me of why I find JavaScript scary in addition to awesome) has a variable that turns “strict mode” on. What this does, just like those of you may know from the Visual Basic days, is turn on a strict mode of additional error checking for code. It helps prevent you from doing all sorts of dumb things, like trying to assign a value to a read-only variable. For more on “strict mode” check out Microsoft’s Strict Mode Page.

The remaining bits of code in the default.js are the handlers for the application activated and checkpoint events. These events are fairly self explanatory, suffice it to say they happen when the application launches and checkpoint fires when a particular checking event happens against the Process Lifetime Management. The Process Lifetime Management handles all of the application suspend, resume and background events.

TDD & BDD For The Win!

Ok, so this isn’t the best example of either really, but to get started we want to wire up an event to a button. But first we want to test if the event is wired up. How does someone tests if an event is wired up in JavaScript? Like this.

[sourcecode language=”javascript”]
test("Where the text box is populated ", function () {
var result = document.getElementById("messageOutput").innerText;
ok(result == "", "should have empty inner text.");
});
[/sourcecode]

Adding a Button & Some Button Functionality

Ok, done with the context. Let’s add a button and make some magic happen. Bring focus to the default.html page and add a button, a text box and the respective components.

[sourcecode language=”html”]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Readingz</title>
<!– These files are included when the project is generated, I don’t really know where they are… –>
<link href="//Microsoft.WinJS.1.0.RC/css/ui-light.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<!– Turned on the testing. –>
<script src="/js/qunitmetro.js"></script>
<script src="/js/default_tests.js"></script>
<!– Default Metro files. –>
<script src="/js/default.js"></script>
<link href="/css/default.css" rel="stylesheet" />
</head>
<body>
<p>Click the button to run the tests for the default.html and default.js code.</p>
<input id="peripheralParameters" type="text" />
<button id="runTests">Run Tests</button>
<p id="messageOutput"></p>
</body>
</html>
[/sourcecode]

NOTE: I made more than a few changes from the default.html included in the previous part of this series. One hard to notice change is that I switched the style sheet from the dark Metro theme to the light Metro theme.

With those additions add a function to the default.js file as shown below and then add the event handler.

[sourcecode language=”javascript”]
(function () {
"use strict";

var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();

app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

} else {

}
args.setPromise(WinJS.UI.processAll());

var runTests = document.getElementById("runTests");
runTests.addEventListener("click", buttonClickHandler, false);
}
};

app.oncheckpoint = function (args) {};

function buttonClickHandler () {
document.getElementById("messageOutput").innerText =
"Parameters Passed: " +
document.getElementById("peripheralParameters").value +
"!";
}

app.start();
})();
[/sourcecode]

I now have one button now working, actually doing something, with a unit tests to verify that the button exists and the event is wired up. Some progress is being made!

If I run the application I get passing tests. That’s it for now. In the next entry we’ll dive deeper into testing and into functionality.

Until next time, happy scripting with the JavaScript on Windows 8.