Last active
December 31, 2015 03:08
-
-
Save ryanlelek/7925026 to your computer and use it in GitHub Desktop.
Node.js API Testing with Nock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// Modules | |
var request = require('request'); | |
var nock = require('nock'); | |
// API You want to use/mock/test | |
var api_url = 'http://api.example.com'; | |
// You can put this into a separate .json file and just require() it | |
// like var users_collection = require('./users.collection.json'); | |
// Beware that JSON requires all properties and values to be in double-quotes ("") to be valid | |
var users_collection = { | |
users : [ | |
{ | |
id : '123abc', | |
username : 'bob' | |
}, | |
{ | |
id : 'def456', | |
username : 'alice' | |
} | |
] | |
}; | |
describe('My API', function () { | |
it('should respond with 200 and an array of User objects', function (done) { | |
// This mock automatically dies after one request | |
// User .persist() to prevent auto-delete and call .done() on captured variable when finished | |
nock(api_url) | |
.get('/users') | |
.reply(200, users_collection, { | |
'Content-Type' : 'application/json' | |
}); | |
request({ | |
url : api_url + '/users', | |
method : 'GET' | |
}, function (error, response, body) { | |
if (error) { return done(error); } | |
response.statusCode.should.equal(200); | |
if (response.headers['content-type'] === 'application/json') { | |
body = JSON.parse(body); | |
} | |
body.should.have.property('users').and.be.instanceOf(Array); | |
body.users.forEach(function (user) { | |
user.should.have.property('id').and.be.length(6); | |
user.should.have.property('username').and.be.type('string'); | |
}); | |
done(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment