I am trying to do a simple test of an external HTTP resource using mocha. Here is my code:
describe('bing.com', function() {
it('should return 200 for a GET request', function() {
var requestify = require('requestify');
requestify.get('http://bing.com')
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
console.log(response.getBody());
done();
});
});
});
The test just says passed but my console.log call is never shown. Is mocha completing before the http response is received?
You don't provide the done callback to your test function:
describe('bing.com', function() {
it('should return 200 for a GET request', function(done) {
...
To catch errors like that you should check your Code with JSHint (or Jslint). Both would inform you that your done() call won't work as the variable is not defined.
Related
I would like to test my simple API that has /groups URL.
I want to make an API request to that URL (using Axios) before all tests begin and make the response visible to all test functions.
I am trying to make the response visible but not able to make it work. I followed a similar case with filling out the DB upfront but no luck with my case.
My simple test file below:
var expect = require('chai').expect
var axios = require('axios')
var response = {};
describe('Categories', function() {
describe('Groups', function() {
before(function() {
axios.get(config.hostname + '/groups').then(function (response) {
return response;
})
});
it('returns a not empty set of results', function(done) {
expect(response).to.have.length.greaterThan(0);
done();
})
});
});
I tried also a sligh modification of before function:
before(function(done) {
axios.get(config.hostname + '/groups')
.then(function (response) {
return response;
}).then(function() {
done();
})
});
but no luck too.
The error I am getting is simply that response isn't changing nor is visible within it. AssertionError: expected {} to have property 'length'
Summarising: How can I pass response from axios inside to in()?
Your first form is incorrect, because you're not returning the chained promise. As such, mocha has no way of knowing when your before is finished, or even that it's async at all. Your second form will solve this problem, but since axios.get already returns a promise, it's kind of a waste not to use mocha's built-in promise support.
As for making the response visible in the it, you need to assign it to a variable in a scope that will be visible within the it.
var expect = require('chai').expect
var axios = require('axios')
var response;
describe('Categories', function() {
describe('Groups', function() {
before(function() {
// Note that I'm returning the chained promise here, as discussed.
return axios.get(config.hostname + '/groups').then(function (res) {
// Here's the assignment you need.
response = res;
})
});
// This test does not need the `done` because it is not asynchronous.
// It will not run until the promise returned in `before` resolves.
it('returns a not empty set of results', function() {
expect(response).to.have.length.greaterThan(0);
})
});
});
I am using express module and below is the code of app.js
app.post('/test_url', function(request, response){
seneca.client({type: 'http',port: '3000',host: 'localhost',protocol: 'http'}).act({role: 'sample_role', cmd: 'save',firstname: request.params.firstname}, function (err, result) {
console.log("Inside Seneca act");
response.json(result);
})
});
Below is the test file where I am writing the test case for above code.
describe("POST /test_url/:firstname", function() {
it("should return status code 200", function(done) {
<b>//here I want to mock the call for seneca.client so that I can test if the call has been made with the required parameters.</b>
<b>//Also I would like to use the above mock object to further mock the call for act so that I can check if the act method has been called with the required parameters.'</b>
//Main purpose behind doing so is that I do not want the seneca methods to get actually called, and only want to test if the call has been made.
request.post("http://localhost:3000/test_url/sara", function(error, response, body) {
//some verification method on the mock object so as to confirm that both the calls i.e 'seneca.client' and 'seneca.client().act' have been called with the appropriate parameters
expect(body).toContain("success");
done();
});
});
});
I tried to mock the seneca calls using jasmine spy and sinon but still the call was actually being going to the method and the the callback function was also invoked resulting in the console.log("Inside Seneca act"); being called, which is not what I expect.
describe("POST /test_url/:firstname", function() {
it("should return status code 200", function(done) {
var senecaCall = sinon.stub(seneca, 'client');
//or spyOn(seneca, "client");
request.post("http://localhost:3000/test_url/sara", function(error, response, body) {
expect(body).toContain("success");
done();
});
});
});
I have some mocha tests I run with Nodejs to test a web server.
Many of the tests should cause the server to return an error, e.g. 400 Bad Request.
Currently the tests are peppered with many copies of the following code:
it('should respond with 400 (Bad Request)', function (){
expect(httpResponse.statusCode).to.equal(httpstatus.BAD_REQUEST);
});
Here's a simplified pseudocode example:
describe('When passing bad JSON data', function(){
var response
before(function(done){
callUrlToInsert(url, badJson, function(err, resp){
response = resp
done()
}
}
it('should respond with 400 (Bad Request)', function (){
expect(httpResponse.statusCode).to.equal(httpstatus.BAD_REQUEST)
})
}
This bugs me because as a programmer I avoid duplicate code wherever possible.
However, putting this into a function does not work:
function verifyItReturnedBadRequest400(httpResponse)
{
it('should respond with 400 (Bad Request)', function (){
expect(httpResponse.statusCode).to.equal(httpstatus.BAD_REQUEST);
});
}
because the call to it() doesn't test the assertion right then; my [limited] understanding is that it() adds the closure to the list of tests. So by the time that check is done, the httpResponse variable has gone out of scope. (I don't understand why that is the case, because in both cases there is a call to it(); why would it matter that in one case it's inside another level of function call? I'm probably missing something with regard to Javascript scoping.)
Is there a common way to avoid all this duplicate code? Or is everyone out there duplicating all their assertion code everywhere? This is my first foray into Mocha so I am probably missing something obvious.
Also, bonus points for explaining why doesn't the function approach work?
Thanks!
There is an article on wiki about this.
https://github.com/mochajs/mocha/wiki/Shared-Behaviours
I guess you have some bugs in your test. Placing it() into wrapper function works fine. Here's a small working demo.
'use strict';
const assert = require('assert');
const xEqualsOne = () => {
it('should be equal 1', () => {
assert.equal(this.x, 1);
});
};
describe('async number', () => {
this.x = 0;
before(done => {
this.x++
setTimeout(done, 100);
});
xEqualsOne();
});
I guess your code looks something like this:
describe('When passing bad JSON data', function(){
var response
before(function(done){
callUrlToInsert(url, badJson, function(err, resp){
response = resp
done()
}
}
verifyItReturnedBadRequest400(httpResponse)
}
Think about it like this:
it() creates a test.
All the calls to it happen before any tests are actually run (you have to create tests before you run them)
The function passed to `before' is run after the tests have been created, but before they are run.
verifyItReturnedBadRequest400 calls it, to create a test, but you're passing in httpResponse right then before any tests have run, so before hasn't run yet either.
You could continue to use that sort of pattern, but you'll need to put the httpresponse in a container so you can pass a reference to it:
describe('When passing bad JSON data', function(){
var data = {};
before(function(done){
callUrlToInsert(url, badJson, function(err, resp){
data.response = resp
done()
}
}
verifyItReturnedBadRequest400(data)
}
and then your verifyItReturnedBadRequest400 becomes:
function verifyItReturnedBadRequest400(data) {
it('should respond with 400 (Bad Request)', function (){
expect(data.response.statusCode).to.equal(httpstatus.BAD_REQUEST);
});
}
I have the following route (express) for which I'm writing an integration test.
Here's the code:
var q = require("q"),
request = require("request");
/*
Example of service wrapper that makes HTTP request.
*/
function getProducts() {
var deferred = q.defer();
request.get({uri : "http://localhost/some-service" }, function (e, r, body) {
deferred.resolve(JSON.parse(body));
});
return deferred.promise;
}
/*
The route
*/
exports.getProducts = function (request, response) {
getProducts()
.then(function (data) {
response.write(JSON.stringify(data));
response.end();
});
};
I want to test that all the components work together but with a fake HTTP response, so I am creating a stub for the request/http interactions.
I am using Chai, Sinon and Sinon-Chai and Mocha as the test runner.
Here's the test code:
var chai = require("chai"),
should = chai.should(),
sinon = require("sinon"),
sinonChai = require("sinon-chai"),
route = require("../routes"),
request = require("request");
chai.use(sinonChai);
describe("product service", function () {
before(function(done){
sinon
.stub(request, "get")
// change the text of product name to cause test failure.
.yields(null, null, JSON.stringify({ products: [{ name : "product name" }] }));
done();
});
after(function(done){
request.get.restore();
done();
});
it("should call product route and return expected resonse", function (done) {
var writeSpy = {},
response = {
write : function () {
writeSpy.should.have.been.calledWith("{\"products\":[{\"name\":\"product name\"}]}");
done();
}
};
writeSpy = sinon.spy(response, "write");
route.getProducts(null, response);
});
});
If the argument written to the response (response.write) matches the test passes ok. The issue is that when the test fails the failure message is:
"Error: timeout of 2000ms exceeded"
I've referenced this answer, however it doesn't resolve the problem.
How can I get this code to display the correct test name and the reason for failure?
NB A secondary question may be, could the way the response object is being asserted be improved upon?
The problem looks like an exception is getting swallowed somewhere. The first thing that comes to my mind is adding done at the end of your promise chain:
exports.getProducts = function (request, response) {
getProducts()
.then(function (data) {
response.write(JSON.stringify(data));
response.end();
})
.done(); /// <<< Add this!
};
It is typically the case when working with promises that you want to end your chain by calling a method like this. Some implementations call it done, some call it end.
How can I get this code to display the correct test name and the reason for failure?
If Mocha never sees the exception, there is nothing it can do to give you a nice error message. One way to diagnose a possible swallowed exception is to add a try... catch block around the offending code and dump something to the console.
I'm working on testing my node.js code with Zombie.js. I have the following api, which is in POST method:
/api/names
and following code in my test/person.js file:
it('Test Retreiving Names Via Browser', function(done){
this.timeout(10000);
var url = host + "/api/names";
var browser = new zombie.Browser();
browser.visit(url, function(err, _browser, status){
if(browser.error)
{
console.log("Invalid url!!! " + url);
}
else
{
console.log("Valid url!!!" + ". Status " + status);
}
done();
});
});
Now, when I execute the command mocha from my terminal, it gets into browser.error condition. However, if I set my API to get method, it works as expected and gets into Valid Url (else part). I guess this is because of having my API in post method.
PS: I don't have any Form created to execute the queries on button click as I'm developing a back-end for mobile.
Any help on how to execute APIs with POST method would be appreciated.
Zombie is more for interacting with actual webpages, and in the case of post requests actual forms.
For your test use the request module and manually craft the post request yourself
var request = require('request')
var should = require('should')
describe('URL names', function () {
it('Should give error on invalid url', function(done) {
// assume the following url is invalid
var url = 'http://localhost:5000/api/names'
var opts = {
url: url,
method: 'post'
}
request(opts, function (err, res, body) {
// you will need to customize the assertions below based on your server
// if server returns an actual error
should.exist(err)
// maybe you want to check the status code
res.statusCode.should.eql(404, 'wrong status code returned from server')
done()
})
})
it('Should not give error on valid url', function(done) {
// assume the following url is valid
var url = 'http://localhost:5000/api/foo'
var opts = {
url: url,
method: 'post'
}
request(opts, function (err, res, body) {
// you will need to customize the assertions below based on your server
// if server returns an actual error
should.not.exist(err)
// maybe you want to check the status code
res.statusCode.should.eql(200, 'wrong status code returned from server')
done()
})
})
})
For the example code above you will need the request and should modules
npm install --save-dev request should