Jesper
Jesper

Reputation: 4555

Testing web API using jasmine and node.js

We've written a RESTful web API which responds to GET and PUT requests using node.js. We're having some difficulties testing the API. First, we used Zombie.js, but it's not well documented so we couldn't get it to make PUT requests:

var zombie = require("zombie");

describe("description", function() {
  it("description", function() {
    zombie.visit("http://localhost:3000/", function (err, browser, status) {
      expect(browser.text).toEqual("A")
    });
  });
});

After that we tried using a REST-client called restler, which would OK, since we don't need any advanced browser simulation. This fails due to the fact that the request seems to be asynchronous - i.e. the test is useless since it finishes before the 'on success' callback is called:

var rest = require('restler');
describe("description", function() {
  it("description", function() {
    rest.get("http://www.google.com").on('complete', function(data, response) {
      // Should fail
      expect(data).toMatch(/apa/i);
    });
  });
});

We'd grateful for any tips about alternative testing frameworks or synchronous request clients.

Upvotes: 5

Views: 9272

Answers (2)

Nick
Nick

Reputation: 1481

For node, jasmine-node from Misko Hevery has asynchronous support and wraps jasmine.

https://github.com/mhevery/jasmine-node

You add a 'done' parameter to the test signature, and call that when the asynchronous call completes. You can also customize the timeout (the default is 500ms).

e.g. from the Github README

it("should respond with hello world", function(done) {
  request("http://localhost:3000/hello", function(error, response, body){
    done();
  }, 250);  // timeout after 250 ms
});

jasmine regular also has support for asynchronous testing with runs and waitsFor, or can use 'done' with Jasmine.Async.

Upvotes: 4

hross
hross

Reputation: 3671

I was curious about this so I did a little more research. Other than zombie, you have a couple of options...

You could use vows with the http library like this guy.

However, I think a better approach might be to use APIeasy, which is apparently built on vows. There is an awesome article over at nodejitsu that explains how to use it.

Another interesting idea is to use expresso if you are using express.

Upvotes: 3

Related Questions