Anup
Anup

Reputation: 9738

Node.js Testing REST API

I am testing for a project for which i used jasmine framework Node js.

I unit tested client code by mocking with $httpBackend.

And now i want to test my server side code & REST api's, but have no idea how to do this?

What is the best approach to test REST api's?

Upvotes: 2

Views: 1591

Answers (2)

user2397627
user2397627

Reputation: 31

Have a look at Chakram, it is a test tool designed for testing REST APIs. It is written on top of Mocha and allows a BDD style.

Upvotes: 1

jfathman
jfathman

Reputation: 808

I recently explored automated testing for my REST API application, and encountered many technology choices. Since my REST API is based on Express, I decided to go with test framework software from the same developer, TJ Holowaychuk, with the idea that his framework for testing his own Express should be very well made and more than adequate for my needs.

I was happy with the resulting combination of Node technologies. I use the Grunt task runner (executed by npm), the Mocha test runner (from TJ), the chai assertion library (using the 'should' assertion style), and supertest (from TJ).

With that test stack, I can easily run an automated test of my REST API. Here is runtime output for a simple test:

[jfathman@cloud api]$ npm test

> [email protected] test /home/jfathman/work/git/api
> node_modules/.bin/grunt test

Running "jshint:file" (jshint) task
>> 3 files lint free.

Running "mochaTest:test" (mochaTest) task

  Test API Proxy REST API
    ? Read config.yaml 
    ? GET /metadata/new, expect json and 200 OK (114ms)
    ? GET /metadata/saved, expect json and 200 OK (100ms)
    ? GET /metadata/deleted, expect json and 200 OK (88ms)
    ? GET /metadata/invalid, expect 400 Bad Request 

  6 passing (326ms)

Done, without errors.

You can also run just the test runner in isolation:

[jfathman@cloud api]$ mocha -R spec

  Test API Proxy REST API
    + Read config.yaml 
    + GET /metadata/new, expect json and 200 OK (95ms)
    + GET /metadata/saved, expect json and 200 OK (102ms)
    + GET /metadata/deleted, expect json and 200 OK (82ms)
    + GET /metadata/invalid, expect 400 Bad Request 

  6 passing (305ms)

It is now a simple matter to run a REST API test suite from the command line during development, or from Jenkins/etc. during CI testing.

Upvotes: 1

Related Questions