I want to be able to grab some response properties and throw them into a variable at times with SuperTest. How can I do this? I don't see the docs doing anything but assertions on the response.
for example I'd like to do something like this:
var statusCode = request(app).get(uri).header.statusCode;
I'd like to do something like this. Because sometimes I like to split out the asserts into seperate Mocha.js it() tests due to the fact I'm doing BDD and so the 'Thens' in this case are based on the expected response parts so each test is checking for a certain state coming back in a response.
for example I'd like to do this with supertest:
var response = request(app).get(uri);
it('status code returned is 204, function(){
response.status.should.be....you get the idea
};
it('data is a JSON object array', function(){
};
Here is an example how you can accomplish what you want:
server file app.js:
var express = require('express');
var app = express();
var port = 4040;
var items = [{name: 'iphone'}, {name: 'android'}];
app.get('/api/items', function(req, res) {
res.status(200).send({items: items});
});
app.listen(port, function() {
console.log('server up and running at %s:%s', app.hostname, port);
});
module.exports = app;
test.js:
var request = require('supertest');
var app = require('./app.js');
var assert = require('assert');
describe('Test API', function() {
it('should return 200 status code', function(done) {
request(app)
.get('/api/items')
.end(function(err, response) {
if (err) { return done(err); }
assert.equal(response.status, 200);
done();
});
});
it('should return an array object of items', function(done) {
request(app)
.get('/api/items')
.end(function(err, response) {
if (err) { return done(err); }
var items = response.body.items;
assert.equal(Array.isArray(items), true);
done();
});
});
it('should return a JSON string of items', function(done) {
request(app)
.get('/api/items')
.end(function(err, response) {
if (err) { return done(err); }
try {
JSON.parse(response.text);
done();
} catch(e) {
done(e);
}
});
});
});
You can see some examples here on the superagent github library since supertest is based on superagent library.
Related
I have created some test cases in node express framework which return successfully. However there are some API calls which need to have authenticated before I can make them. I can call the API that requires authentication in reactJs via ajax and It give a success response, however when I set the same header in chai-Http, it fails with invalid token.
var chai = require('chai');
var should = chai.should();
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var server = require('../app');
describe('routes : index', function() {
var token = '';
beforeEach(function(done) {
done();
});
before(function(done) {
chai.request(server)
.post('/doSignin')
.send({uname:'ruzan#test.com',password:'123123'})
.end(function(err, res) {
res.redirects.length.should.equal(0);
res.status.should.equal(200);
token = res.body.user.token;
res.type.should.equal('application/json');
done();
});
});
afterEach(function(done) {
done();
});
describe('Test FolderController', function() {
it('should list all the folders', function(done) {
console.log(token); // here it print the same token
chai.request(server)
.get('/notes/get-notes')
.set('prg-header' , token)
.end(function(err, res) {
// console.log(res);
res.status.should.equal(200);
done();
});
});
});
});
ReactJs:
$.ajax({
url: '/notes/get-notes',
method: "GET",
dataType: "JSON",
headers: { 'prg-header':loggedUser.token }
}).done( function (data, text) {
console.log(data);
if(data.status.code == 200){
// it come here the data
}
}.bind(this));
I'm starting my project based on this repo:
https://github.com/madhums/node-express-mongoose
The first thing I decided to do was write tests, so I went to the test file, and it looks something like this:
var mongoose = require('mongoose');
var should = require('should');
var request = require('supertest');
var app = require('../server');
var context = describe;
// other stuff you want to include for tests
before(function (done) {
// clear db and other stuff
done();
});
describe('Users', function () {
describe('POST /users', function () {
it('should create a user', function (done) {
request(app)
.post('/users')
.field('name', 'foo')
.field('email', 'foo')
.field('password', 'foo')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res){
console.log(err);
if(err){
console.log("error");
}
// console.log(res);
});
done();
});
});
});
after(function (done) {
// do some stuff
done();
});
I haven't actually created the route, so the test should be failing, and I even do get an error on .end, so any idea why is the test not failing?
My console shows me this when I run npm test
Express app started on port 3000
Users
POST /users
✓ should create a user
[Error: expected "Content-Type" matching /json/, got "text/html; charset=utf-8"]
error
1 passing (653ms)
The problem is that your test is asynchronous, but your code is synchronous. Specifically, the done() line is always called.
You need to move the done() line into the .end block, and add done(err) for the error case, like this:
.end(function(err, res){
if(err){
console.log("error");
done(err);
}
else {
console.log(res);
done();
}
});
This is more or less a duplicate of supertest test express middleware
but after a year, I figured I'd start a new question.
var express = require('express');
var request = require('supertest');
var app1 = express();
app1.get('/myapp', function (req, res) {
res.send(200, { name: 'myapp' });
});
request = request(app1);
it('should fail', function () {
request
.get('/hahahahahahahaha')
.expect(123);
});
As far as I can tell, that will always erroneously pass. The fact that the path is wrong and is expecting a different status code doesn't matter.
And - more generically (without Express), it looks like this always passes, also:
it('should fail', function () {
request('http://thisdoesnotexist.mydomain')
.get()
.expect(200);
});
This doesn't work either:
it('should fail', function () {
request('http://thisdoesnotexist.mydomain')
.get()
.expect(200)
.end(function (err, res) {
if (err) {
throw err;
}
});
});
Any thought as to why this happens, or how to actually test such a scenario?
With supertest you need to terminate your chain somehow.
expect will take a finished callback as the second parameter, and you can use the build in mocha callback for this. Like so:
describe('potato', function() {
it('should fail', function(done) {
request
.get('/hahahahahahahaha')
.expect(123, done);
});
});
Specifying a done option like this will instruct mocha to wait until it's heard back from you before proceeding to the next test.
The difference is the parameter: done
describe('XXX', function() {
it('XXX', function() {
// always passing
})
})
describe('YYY', function(done) {
it('YYY', function() {
// always passing
})
})
describe('ZZZ', function() {
it('ZZZ', function(done) {
// normal
})
})
I'm trying to test my app, and it always returns an error of connect ECONNREFUSED. I made a simple example to show what's happening. Here's my controller (CompoundJS code):
load('application');
action('test', function() {
var obj = {success: true, data: 'blah'};
send(obj);
});
action(function show(data) {
var http = require('http');
var options = {
path: '/getTest',
port: process.env.PORT // without this, http fails because default port is 80
};
var req = http.get(options, function(res) {
var data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
data = JSON.parse(data);
return send(data);
});
});
req.on('error', function(e) {
return send({success: false, data: e.message}); // returns "connect ECONNREFUSED"
});
});
So when I have the app running, I can hit /test (which is the show method there) and /getTest just fine without any errors. However, when I try to run the following test code, I get the error as stated above, and the issue comes down to that http.get, as I can get into the show function just fine.
var app, compound
, request = require('supertest')
, sinon = require('sinon');
function TestStub() {
return {
};
}
describe('TestController', function() {
beforeEach(function(done) {
app = getApp();
compound = app.compound;
compound.on('ready', function() {
done();
});
});
/*
* GET /tests
* Should render tests/index.ejs
*/
it('should render "index" template on GET /tests', function(done) {
request(app)
.get('/test')
.end(function(err, res) {
console.log(res.body);
done();
});
});
});
Any ideas on how to fix this? Cross posted from the CompoundJS Google Group.
I'm trying to test the get function:
exports.get = function(req, res) {
Subscriptions
.find(req.params.id)
.success(function(subscription) {
if (subscription) {
res.json({message: "Success"}, 200);
} else {
res.json({message: "Not found"}, 404);
}
})
.error(function(error) {
res.json({message: "Internal server error"}, 500);
});
};
Specifically, I don't really care if it hits the database, I only want to test the scenarios where the success and error events occur. I'm using sequelize.js as my orm to handle the database. I've gotten a test up and running, but its a bit nasty, with the timeout. Is there a better way of doing this? Here's the test I've written so far:
var express = require('express')
, sinon = require('sinon')
, subscription = require('app/controllers/subscriptions')
, Subscriptions = require('app/models/subscriptions')
;
describe('subscription controller', function() {
beforeEach(function() {
this.mockResponse = sinon.mock(express.response);
});
afterEach(function() {
this.mockResponse.restore();
});
describe('GET /subscriptions/:id', function() {
it('should return a json response', function(done) {
var request = {
params: {
id: 'identifier'
}
};
var expectedResponse = {
subscriptions_uri : "/subscription/identifier"
};
this.mockResponse
.expects('json')
.once()
.withArgs(expectedResponse);
subscription.get(request, express.response);
setTimeout(function() {
done();
}, 500);
});
});
});
I decided to use the supertest library, which made testing my controller incredibly easy:
var express = require('express')
, subscription = require('app/controllers/subscriptions')
, request = require('supertest')
, app = express()
;
describe('subscription controller', function() {
describe('GET /subscriptions/:id', function() {
it('should return a json response', function(done) {
var expectedBody = {
subscriptions_uri : "/subscription/identifier"
};
request(app)
.get('/subscriptions/identifier')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(expectedBody)
.expect(200, done);
});
});
});