Skip to content

Instantly share code, notes, and snippets.

@listochkin
Created December 13, 2014 11:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save listochkin/17b2b3dfd69b4ea3eaa3 to your computer and use it in GitHub Desktop.
Save listochkin/17b2b3dfd69b4ea3eaa3 to your computer and use it in GitHub Desktop.
Async ccode with Callbacks, Promises and Generators
/* jshint node:true, mocha:true, eqnull:true, esnext:true */
'use strict';
var chai = require('chai'),
assert = chai.assert,
expect = chai.expect;
var request = require('request');
var jsdom = require("jsdom");
describe('Simple Node tests', function () {
it('should pass', function () {
assert(1 == '1', 'WHA?');
expect(1).to.equal(1);
});
it('Should load a page', function (done) {
request('https://www.npmjs.org/', function (error, response, body) {
assert(error == null, 'Error connecting to host');
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Http tests', function () {
it('Should load # of releases', function (done) {
request('http://nodejs.org/dist/', function (error, response, body) {
assert(error == null, 'Error connecting to host');
expect(response.statusCode).to.equal(200);
jsdom.env(response.body, function (error, window) {
var releaseCount = window.document.querySelectorAll("a").length;
expect(releaseCount).to.be.greaterThan(200);
done();
});
});
});
var promisify = require('bluebird').promisify,
http = promisify(function (options, cb) {
request(options, function (error, response, body) {
cb(error, response);
})
}),
dom = promisify(jsdom.env);
it('Should load # of releases with Promises', function (done) {
http('http://nodejs.org/dist/').then(function (response) {
expect(response.statusCode).to.equal(200);
return dom(response.body);
}).then(function (window) {
var releaseCount = window.document.querySelectorAll("a").length;
expect(releaseCount).to.be.greaterThan(200);
done();
});
});
var co = require('co');
it('Should load # of releases with Generators', function (done) {
co(function *() {
var response = yield http('http://nodejs.org/dist/');
expect(response.statusCode).to.equal(200);
var window = yield dom(response.body);
var releaseCount = window.document.querySelectorAll("a").length;
expect(releaseCount).to.be.greaterThan(200);
}).then(function () {
done();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment