NodeJs and Mocha testing the response - angularjs

Is it possible to test the response from NodeJs using Mocha?
A GET request is made using $http from AngularJs to NodeJs. On success of the request this function is called:
var successCallback = function (data) {
var SUCCESS_STATUS_CODE = 200;
response.set('Content-Type', 'application/json');
response.send({
statusCode: SUCCESS_STATUS_CODE,
data: data
});
};
I have tried to use Sinon to spy on the function and also Mocha to check the request but I cannot get them to work. What is the best way to write a test to check that the output from "response.send"?

To test a response of a HTTP call from Node.JS, you could use superagent
Create a folder and install inside mocha and superagent:
$ npm install superagent
$ npm install mocha
Then create a file called something like test.js with this code:
var request = require('superagent');
var assert = require('assert');
var URL = 'https://www.google.com.bo/#q=nodejs';
describe('Testing an HTTP Response', function () {
it('should have a status code 200', function (done) {
this.timeout(9000);
request
.get(URL)
.end(function (err, response) {
assert.equal(response.status, 200);
done();
});
});
});
then you can run it with mocha
$ mocha

Related

consume a web service in nodejs

Normally in angular.js I was used to consuming a web service GET, in which I passed 2 parameters, as follows.
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+tweet.lat+','+tweet.long+'&key=AIzaSyBZVOSPh0Z4mv9jljJWzZNSug6upuec7Sg')
.then(function(result){
}, function(error){
}
How can I get this same result directly in nodejs?. thank you very much.
There are several way to do this. A lot of people use the request module, which makes things about the same as angular:
You'll need to install request (https://www.npmjs.com/package/request) with:
npm install request
and then:
var request = require('request');
request(url, function (error, response, body) {
// do stuff with response & body.
});
If you want promises, there is also a request-promise module available on npm (https://www.npmjs.com/package/request-promise).
npm install --save request
npm install --save request-promise
You need both request and request-promise in this case.
var request = require('request-promise');
request(url)
.then(function (result) {
// do stuff with result
})
.catch(function (err) {
//error
});
Also you can use the http module built into node, but then you'll need to manage the stream yourself.

Mock $http with configuration parameters

I'm applying some tests in an existing AngularJS application in order to ensure it's correct behaviour for future changes in the code.
I am pretty new with Jasmine & Karma testing, so I've decided to start with a small and basic service which performs an http request to the backend, and waits for the result with a promise, nothing new.
Here's the service method to test:
function getInformedConsent(queryParameters) {
var def = $q.defer(),
httpParameters = {
url: ENV.apiEndpoint + '/urlResource',
method: 'GET',
params: queryParameters,
paramSerializer: '$httpParamSerializerJQLike'
};
$http(httpParameters)
.then(
function (response) {
def.resolve(response);
},
function (error) {
def.reject(error);
}
);
return def.promise;
}
And here my test:
it('getInformedConsent method test', function() {
$httpBackend.expectGET(/.*\/urlResource?.*/g)
.respond(informedConsentJson.response);
var promise;
promise = InformedconsentService.getInformedConsent(informedConsentJson.queryParameters[0]);
promise
.then(function(response) {
console.log(response);
expect(response).toEqual(informedConsentJson.response);
});
$httpBackend.flush();
});
informedConsentJson as you can supose, is a fixture with input and the expected output.
Reading AngularJS documentation, I decided to use $httpBackend, because it's already a mock of $http service, so I thought it could be useful.
The problem is that somewhere in the code, someone is broadcasting a "$locationChangeStart" event and executing
$rootScope.$on('$locationChangeStart', function (event,current,old) {
/* some code here */
});
in app.js.
I'm not trying to change the URL, i'm just trying to get some data from the mocked backend.
I asume that is because I'm not using $http mock ($httpBackend) as it should be used.
Anyone can help me with $http with configuration JSON mock?
It's freaking me out.
Thank you all in advance for your time and your responses

$httpBackend doesn't respond in Protractor test

I'm trying to write a test in Protractor/Jasmine that depends upon my being able to see the headers sent in an HTTP request. To that end I'm trying to create a mock endpoint with $httpBackend that will respond to a call with the headers themselves, allowing me to look into them in my test. My code is as follows:
describe('Headers', function () {
it('should include X-XSRF-TOKEN on HTTP calls', function () {
browser.addMockModule('httpBackendMock', function () {
angular.module('httpBackendMock', ['CorsApp', 'ngMockE2E'])
.run(function ($httpBackend) {
$httpBackend.whenGET('/xsrftest')
.respond(function (method, url, data, headers) {
return headers;
});
})
});
loginPage.get();
browser.executeAsyncScript(function (callback) {
var $http = angular.injector(['ng']).get('$http');
$http.get('/xsrftest')
.then(function (response) {
callback(response);
});
})
.then(function (response) {
console.log(response);
});
});
});
I've tried to follow the patterns set out in many resources for utilizing $httpBackend in protractor testing. However, when I run this test, I get a Protractor timeout. It seems as though the $http.get call never receives a response, hence the callback is never called and so the executeAsyncScript call times out. If I put in a dummy call to the callback that's not dependent on the $http.get, it works as expected.
What am I doing wrong in setting up $httpBackend? How can I get it to respond to my $http request?
Thanks!

Unit testing with $httpbackend mocks and typescript

I'm trying to unit test a method that makes an http request with the $http service, however the $httpbackend mock does not seem to be intercepting the request - I get a Error: No pending request to flush ! error.
My test is as follows:
/// <reference path="../typings/tsd.d.ts" />
/// <reference path="../dist/ngJwtAuth.d.ts" />
var expect = chai.expect;
describe('Service tests', () => {
var $httpBackend:ng.IHttpBackendService;
var ngJwtAuthService:NgJwtAuth.NgJwtAuthService;
beforeEach(()=>{
module('ngJwtAuth');
inject((_$httpBackend_, _ngJwtAuthService_) => {
$httpBackend = _$httpBackend_;
if (!ngJwtAuthService){ //dont rebind, so each test gets the singleton
ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider
}
})
});
afterEach(() => {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should be an injectable service', () => {
return expect(ngJwtAuthService).to.be.an('object');
});
it('should retrieve a json web token', () => {
var user = {
email: 'joe.bloggs#example.com',
password: 'password'
};
$httpBackend.expectGET('/api/auth/login', (headers) => {
return headers['Authorization'] == 'Basic '+btoa(user.email+':'+user.password);
});
var promisedToken = ngJwtAuthService.authenticate(user.email, user.password);
promisedToken.then((res) => {
console.log('res', res);
});
$httpBackend.flush();
});
});
The results I get is
Start:
Service tests
✔ should be an injectable service
✖ should retrieve a json web token
✖ "after each" hook
Finished in 0.055 secs / 0.004 secs
SUMMARY:
✔ 1 tests completed
✖ 2 tests failed
FAILED TESTS:
Service tests
✖ should retrieve a json web token
Chrome 43.0.2357 (Mac OS X 10.10.3)
Error: No pending request to flush !
at Context.<anonymous> (base/test/tmp/test.js?7ade37b85a3e515024b3ce23ba6d9fc4c70ddcc2:104:22)
✖ "after each" hook
Chrome 43.0.2357 (Mac OS X 10.10.3)
Error: Unsatisfied requests: GET /api/auth/login
at Context.<anonymous> (base/test/tmp/test.js?7ade37b85a3e515024b3ce23ba6d9fc4c70ddcc2:86:22)
The offending method that I am testing is
public authenticate(username:string, password:string): ng.IPromise<Object>{
var authHeader = NgJwtAuthService.getAuthHeader(username, password);
var requestConfig:ng.IRequestConfig = {
method: 'GET',
url: this.getLoginEndpoint(),
headers: {
Authorization : authHeader
},
responseType: 'json'
};
return this.$http(requestConfig);
}
The whole project can be found at https://github.com/spira/angular-jwt-auth
OK, I worked it out after a bit of playing around. Turns out the solution was to make sure that $httpbackend was not redeclared for each function. This looks like this:
inject((_$httpBackend_, _ngJwtAuthService_) => {
if (!ngJwtAuthService){ //dont rebind, so each test gets the singleton
$httpBackend = _$httpBackend_;
ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider
}
})
As I wanted each test to use the same service (the service is mutable), I had to include the $httpBackend = _$httpBackend_; line inside the if block.

How to verify that an http request is not made at all?

how to verify that none of http request method are invoked to do any request. I have this code :
$scope.getSubnetsPageDetails = function (pageNumber) {
$http.get(URLS.subnetsPagesCount(pageNumber)).success(function (response) {
$scope.pageDetails = response;
}).error(function (response, errorCode) {
});
};
and this test :
it("should not allow request with negative page number", function () {
scope.getSubnetsPageDetails(-1);
//verify that htt.get is not invoked at all
});
How to verify that http.get is not invoked ?
You can test that no calls are made by using the verifyNoOutstandingRequest() method from the $httpBackend mock.
Usually those kind of verification is done in the afterEach section of a Jasmine's tests. On top of this it is common to call another method, verifyNoOutstandingExpectation() to verify that all the expected calls were actually invoked.
Here is the code, where you need to inject the $httpBackend mock:
var $httpBackend;
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
}));
then do you test and at the end:
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
Of course you could invoke the $httpBackend.verifyNoOutstandingRequest() inside an individual test. The mentioned http://docs.angularjs.org/api/ngMock.$httpBackend page has a wealth of information on the topic.

Resources