Skip to content

Instantly share code, notes, and snippets.

@dangoor
Created April 1, 2013 13:51
Show Gist options
  • Save dangoor/5285061 to your computer and use it in GitHub Desktop.
Save dangoor/5285061 to your computer and use it in GitHub Desktop.
Some notes about node unit testing

jasmine-node from the command line helps with a quick TDD cycle.

Here's a snippet from Validation.spec.js:

describe("Package Validation", function () {
    it("should handle a good package", function (done) {
        packageValidator.validate(basicValidExtension, {}, function (err, result) {
            expect(err).toBeNull();
            expect(result.errors.length).toEqual(0);
            var metadata = result.metadata;
            expect(metadata.name).toEqual("basic-valid-extension");
            expect(metadata.version).toEqual("1.0.0");
            expect(metadata.title).toEqual("Basic Valid Extension");
            done();
        });
    });

done is very straightforward.

Rewire calls itself "dependency injection for node.js applications". It's very handy for testing.

  • Use it like require
  • Monkey with anything private in the module!
var rewire     = require("rewire"),
    repository = rewire("../lib/repository"),
    path       = require("path");

var testPackageDirectory = path.join(path.dirname(module.filename), "data"),
    basicValidExtension  = path.join(testPackageDirectory, "basic-valid-extension.zip");

var originalValidate = repository.__get__("validate");

describe("Repository", function () {
    beforeEach(function () {
        // Clear the repository
        repository.configure({
            storage: "./ramstorage"
        });
    });
    
    afterEach(function () {
        repository.__set__("validate", originalValidate);
    });
    
    function setValidationResult(result) {
        repository.__set__("validate", function (path, options, callback) {
            callback(null, result);
        });
    }

In the example above, you can see me manipulating validate which is a function imported into the repository module.

Tip: Google node mock foo (s3 in this case) and you can sometimes find a prebuilt mock.

Drawback: right now, my Node tests in Brackets do not run automatically.

  • could pipe the results back to our test runner
  • should be easier to make it run in Travis

brackets-registry tests are jasmine-node running in Travis. Instant CI!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment