Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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