EzDevInfo.com

buster

A powerful suite of automated test tools for JavaScript. Welcome! Buster.JS is... — Buster.JS 0.7 documentation

Node.js modules for unit-testing

Suppose I have a web application, which uses jquery for ajax and UI. Now I would like to add unit-tests to it. I would like the unit-tests to run in a single process without launching browsers and separate web servers and I hope it is doable with the node.js and the following node modules:

  • buster.js
  • jquery node module
  • jsdom node module

Am I missing something? Is there any example of such unit-tests?


Source: (StackOverflow)

How to test with buster remote fetching file function, which works but works with callback

How to test function which fetch file from remote server with Buster ? I wrote test like

buster.testCase("Remote fetch file", {
    "test it": function () {
        assert(true);
    },

    "remote fetch file" : function (){
        remoteFileFetchingFunction(credentials, 'whoami', function (err, result) {
            assert.equals(result, 'John');
        });
    }

});

But always get error like Failure: No assertions!


Source: (StackOverflow)

Advertisements

Buster.js dependency error with jQuery: window is not defined

Whenever I attempt to run my unit tests (written with buster and executed user buster test) and include jQuery (since my library depends on it). I get the following error:

./test/deps/jquery-1.7.2.min.js: window is not defined

Here's my buster.js config file: var config = module.exports;

config["GitJs Tests"] = {
    rootPath: "../",
    environment: "node",
    sources: [
        "src/Gitjs.js"
    ],
    deps: [
        "test/deps/*.js" // Jquery is in here
    ],
    tests: [
        "test/test_constructor.js"
    ]
};

Why do I get this error and how do I fix it?


Source: (StackOverflow)

How do I hook onto suite:start / end with Buster.js?

I want to create a global setup/teardown method with Buster.js, but I can't understand how to do it. The documentation speaks of a "suit:start" and "suite:end"-event which looks like what I'm after, but I don't understand how to hook onto it. Anyone?


Source: (StackOverflow)

Buster.js - ReferenceError : assert is not defined, where I did wrong?

This is the error message:

 ReferenceError: assert is not defined
    at Object.buster.testCase.says hello to name var (./test/test-script.js:12:40)

file config buster.js:

var config = module.exports;

config["myTests"] = {
    rootPath: "../",
    environment: "browser",
    libs: ["*.js"],
    sources: ["start/script.js" ],
    tests: ["test/test-script.js"]
}; 

tree files:

main_dir/start : index.html; script.js
main_dir/test : buster.js; buster_063.js; test-script;
main_dir : jQuery.js; Mootools.js;

test-script.js:

buster.testCase("Hello", {
    "says hello to name var": function(){ assert.equals( hello("Fulvio"), "Hello Fulvio" ); }
});

Source: (StackOverflow)

How do wildcards in BusterJS test paths get interpreted?

At the command line, what are the rules for using wildcards to specify the path to tests that BusterJS should run? How do such paths get interpreted by BusterJS? That is, the value provided for the option -t as in the following:

$ buster-test -t <some path that contains wildcards>


Source: (StackOverflow)

How can I pass env vars to buster.js?

I have a buster.js test. I need to pass some data to the test via an environment variable. How can I do this?


Source: (StackOverflow)

sinon stub for window.location.search

I am trying to test a simple function that makes a call to window.location.search. I'm trying to understand how to stub this call so that I can return a url of my choosing.

function:

getParameterByName: (name) =>    
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
  regexS = "[\\?&]" + name + "=([^&#]*)"
  regex = new RegExp(regexS)    
  results = regex.exec(window.location.search) //Stub call to window.location.search
  if(results == null)
    return ""
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "))

Test case:

describe "Data tests", () ->
  it "Should parse parameter from url", () ->        
    data = new Data()

    console.log("search string: " + window.location.search) //prints "search string:"
    window.location.search = "myUrl"
    console.log("search string: " + window.location.search) //prints "search string:"
    console.log(data.getParameterByName('varName'))

    expect(true).toBe(true)

My original attempt was to return a value directly like so:

sinon.stub(window.location.search).returns("myUrl")

This, of course, doesn't work. I don't think I'm specifying the stub correctly, but it shows my intent.

Any ideas on how to solve this would be greatly appreciated.


Source: (StackOverflow)

A Good Example On How to Use BusterJs Resource Config Option?

I'm looking for a good example that shows how to use busterJS's resource property in the buster.js config file to include a .json file in a test case.

From the documentation:

resources

Additional resources that will be made available for test runs, but not explicitly loaded. Value is an array of resources. Resources are served from a context path on the server. To request a resource in your test runs, you need to scope resource paths with buster.env.contextPath. The resource /some/cookies.json can be requested as jQuery.get(buster.env.contextPath + "/some/cookies.json");

It also states:

A "resource" is something exposed on the server when you run browser tests using buster-server and buster-test. Exposing the resource /something.json allows you to request it in your tests using e.g. jQuery.ajax({ url: "something.json" });.

And here's the example they give:

    config["Browser build tests"] = {
    environment: "browser",
    libs: ["lib/**.js"],
    resources: [
        "src/**.js",
        { path: "/mylib.min.js",
          combine: ["src/base.js", "src/dom.js"] }
    ],
    sources: ["/mylib.min.js"],
    tests: ["test/**.js"]
};

However, they don't give a solid example of using the JSON file in a unit test. When I've tried following their examples, jQuery throws a 404 when I try doing jQuery.ajax({ url: "[my-file-name-here]" }).

Has anyone ever successfully used this feature?


Source: (StackOverflow)

How can I use Require.js and Buster.js together?

I'm trying to get started with Buster.js, and I installed both buster and buster-amd, but even so my use of Require.js is causing problems. My buster.js file looks like this:

var config = module.exports;
config["My tests"] = {
    autoRun: false,
    environment: "browser", // as opposed to "node"
    extensions: [require("buster-amd")],
    rootPath: "../",
    sources: ['ext/require/require.js'],
    tests: ["buster-test/*-test.js"]
};

and my test like this:

define(['buster-test/buster'
], function(buster) {
    buster.spec.expose(); // Make some functions global
    describe("A Fake Test", function () {
        it("can be instantiated", function () {
            console.log('test')
        });
    });
    buster.run()
});

But when I try to run the above, I get:

Uncaught exception: ./buster/load-all.js:1 Uncaught ReferenceError: require is not defined
TypeError: uncaughtException listener threw error: Cannot read property 'id' of undefined
    at Object.module.exports.uncaughtException (/usr/lib/node_modules/buster/node_modules/buster-test-cli/lib/runners/browser/progress-reporter.js:42:50)
    at notifyListener (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/bane/lib/bane.js:49:35)
    at Object.object.emit (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/bane/lib/bane.js:127:17)
    at Object.module.exports.bane.createEventEmitter.emitCustom (/usr/lib/node_modules/buster/node_modules/buster-test-cli/lib/runners/browser/remote-runner.js:289:14)
    at /usr/lib/node_modules/buster/node_modules/buster-test-cli/lib/runners/browser/remote-runner.js:92:16
    at PubSubClient.on._handler (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/lib/pubsub-client.js:73:43)
    at Object.Faye.Publisher.trigger (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:385:19)
    at Object.Faye.extend.Set.Faye.Class.distributeMessage (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:668:30)
    at Object.Faye.Client.Faye.Class._deliverMessage (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:1070:20)
    at Object.Faye.Client.Faye.Class.receiveMessage (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:1007:12)

Has anyone seen anything like this before, and if so do you have any suggestions as to what I'm doing wrong?

P.S. If I remove the extensions: line I get a similar error, except that it complains about define instead of require. So it seems like the failure to find require is happening inside the plug-in ... but I have no idea how to provide Require to the plug-in.


Source: (StackOverflow)

buster.js testing cannot load my js-files

I've been banging my head at the wall since yesterday (only interrupted by a great Bruce Springsteen concert last night... ;-)

I am trying to add some JS testing to an existing (Rails) project. Basically the folder structure is this:

.
├── app
│   └── assets
│       └── javascripts
│           └── strftime.js
└── spec
    ├── buster.js
    └── javascripts
        └── strftime.test.js

In this very simple example I've taken the buster example from here https://gist.github.com/cjohansen/1904218 to be sure that everything worked before moving files around.

My buster.js looks like this:

var config = exports;

config["Server tests"] = {
    // sources: ["../app/assets/javascripts/strftime.js"],
    tests: ["javascripts/strftime.test.js"],

    env: "node"
};

and I've tried modifying the first 5 lines of strftime.test.js to this:

if (typeof require == "function" && typeof module == "object") {
    buster = require("buster");

    require("../app/assets/javascripts/strftime.js");
}

Currently when I run buster test, I get this:

$ buster test
Failed requiring ./spec/javascripts/strftime.test.js: Cannot find module '../app/assets/javascripts/lib/strftime.js'

If I try to uncomment the sources line, buster test fails silently - even if I try to run it with high debug level.

I've zipped the entire example (2 KB) and put it here, if anyone would like try give it a try: http://gehling.dk/b2.zip

UPDATE: I've managed to require the js-file successfully by supplying the path relative to my test-js file:

if (typeof require == "function" && typeof module == "object") {
    buster = require("buster");

    require("../../app/assets/javascripts/strftime.js");
}

But I still have the problem with buster failing silently, if I add the sources parameter.

TIA

/ Carsten


Source: (StackOverflow)

Issues using BusterJS, ExpressJS, and SuperTest

I'm having some issues testing routes using ExpressJS + BusterJS + SuperTest.

var app = require("../../app/app.js"),
buster = require("buster"),
expect = buster.referee.expect,
http = require('http'),
request = require('supertest');

buster.spec.expose();

describe("V2 API - group/get", function () {
    var server;

    beforeEach(function() {
        server = http.createServer(app).listen(app.get('port'), function () {
            console.log('Express server listening on port ' + app.get('port'));
        });
    });

    it("is accessable", function() {
        request(server)
          .get('/')
          .expect(200)
          .end(function(err, res){
             server.close();
             expect(err).toBe(null);
           });
    });
});

When I run this test, I get:

Failure: V2 API - group/get is accessible
No assertions!

1 test, 0 assertions, 1 runtime ... 1 failure
Express server listening on port 3000

Which seems wrong, because I actually do have an assertion. The problem is that it doesn't get called unless there is an error.

Another issue is that if I have multiple 'if' blocks, the server doesn't restart between them. I might be using the node + express + buster + supertest stack wrong, so any help with how to test these routes would be greatly appreciated.


Source: (StackOverflow)

Importing other .js files in Buster.js tests

I'm making my first attempt at Javascript testing, with Buster.js

I've followed the instructions at the Buster site to run "states the obvious" test. However, I haven't been able to import any of my existing .js files into the tests.

For instance, I have a file js/testLibrary.js, containing:

function addTwo(inp) {
  return inp+2;
}

and a file test/first-test.js, containing:

// Node.js tests
var buster = require("buster");
var testLibrary = require("../js/testLibrary.js");
var assert = buster.referee.assert;

buster.testCase("A module", {
    "Test The Library": function() {
            result = addTwo(3);
            console.log(result);
            assert(true, 'a message for you');
    }
});

Running buster-test gives:

Error: A module Test The Library
    ReferenceError: addTwo is not defined
    [...]

Replacing result = addTwo(3); with result = testLibrary.addTwo(3); gives:

Error: A module Test The Library
    TypeError: Object #<Object> has no method 'addTwo'
    [...]

I'm probably missing something really basic, but at present, I'm completely stumped. Can someone point me in the right direction?


Source: (StackOverflow)

Why do we do delete [object].[property] inside of tearDown (unit testing)

Code:

var buster = require('buster'),
    NumberCruncher = require('../src/NumberCruncher');

buster.testCase('Number Cruncher', {
    setUp: function() {
        this.numberCruncher = new NumberCruncher();
    },
    tearDown: function() {
        delete this.numberCruncher;
    },
    'constructor returns numberCruncher': function() {
        assert(this.numberCruncher instanceof NumberCruncher);
    },
    'object constructor correct': function() {
        assert.equals(this.numberCruncher.constructor, NumberCruncher);
    },
    'can add numbers': function() {
        buster.assert.equals(this.numberCruncher.add(5,3), 8, 'NumberCruncher cannot add');
    }
});

Background:

In setUp, we are creating an object and setting it as a property of this (the testcase). In tearDown we are deleting said property.

Question:

If you had to explain the thought or reason behind the practice of deleting object properties in the tearDown method, what would you say? Why is this a good thing? Does it have benefits? Does it only have benefits when scaled to really big objects?

My Thoughts:

My reasoning (which may be wrong), is that we are guaranteeing garbage collection after each test is run.


Source: (StackOverflow)

Has buster.js / sinon something like `jasmine.any()`?

Developing a callback-driven API, I would like to express that a certain function as to be called with a specific set of parameters and “any” function (the callback).

Jasmine can do the following:

var serviceFunction = jasmine.createSpy();
var functionUnderTest = create(serviceFunction);
var thing = 'arbitrary/thing'

functionUnderTest(thing);
expect(serviceFunction).toHaveBeenCalledWith(thing, jasmine.any(Function));

Have sinon/buster.js similar capabilities? So far I’m testing only the first argument, but I’d really like to express the need for a callback in the test.

This is what I have so far:

var serviceFunction = this.spy(); // or `sinon.spy()`
var functionUnderTest = create(serviceFunction);
var thing = 'arbitrary/thing'

functionUnderTest(thing);
assert.calledWith(serviceFunction, thing);

Source: (StackOverflow)