If you make a request to sails via supertest, the response hangs if you return an error.
Here, we have already lifted sails, and will run this as an integration test against a live db.
var sails = require('sails').lift();
var request = require('supertest');
var app = sails.hooks.http.app;
describe('The creation of a model',function(){
it('should not create a duplicate',function(done){
var user = request.agent(app);
user
.post('/api/create')
.end(function(err,res){
//never gets here, your test will hang
done();
});
});
});
//controller.js
module.exports = {
// /api/create routes here
create:function(req,res){
var params = {
name:"invalid"
};
SomeAction(params,function(err,results){
if (err) {
//the problem is here.
return err;
}
res.json(results);
});
}
};
If you make a supertest request to sails and the function just returns a value, ie. you don't use res.send() or res.json() it will hang the request for supertest. Here's the right way to do it:
var sails = require('sails').lift();
var request = require('supertest');
var app = sails.hooks.http.app;
describe('The creation of a model',function(){
it('should not create a duplicate',function(done){
var user = request.agent(app);
user
.post('/api/create')
.end(function(err,res){
//never gets here, your test will hang
done();
});
});
});
//controller.js
module.exports = {
// /api/create routes here
create:function(req,res){
var params = {
name:"invalid"
};
SomeAction(params,function(err,results){
if (err) {
//you need to send a response to the
res.json({
error:"an error occured"
});
}
res.json(results);
});
}
};
Related
I want to achieve something like this:
call my website url https://mywebsite/api/something
then my next.js website api will call external api
get external api data
update external api data to mongodb database one by one
then return respose it's status.
Below code is working correctly correctly. data is updating on mongodb but when I request to my api url it respond me very quickly then it updates data in database.
But I want to first update data in database and then respond me
No matter how much time its take.
Below is my code
export default async function handler(req, res) {
async function updateServer(){
return new Promise(async function(resolve, reject){
const statusArray = [];
const apiUrl = `https://example.com/api`;
const response = await fetch(apiUrl, {headers: { "Content-Type": "application/json" }});
const newsResults = await response.json();
const articles = await newsResults["articles"];
for (let i = 0; i < articles.length; i++) {
const article = articles[i];
try {
insertionData["title"] = article["title"];
insertionData["description"] = article["description"];
MongoClient.connect(mongoUri, async function (error, db) {
if (error) throw error;
const articlesCollection = db.db("database").collection("collectionname");
const customQuery = { url: article["url"] };
const customUpdate = { $set: insertionData };
const customOptions = { upsert: true };
const status = await articlesCollection.updateOne(customQuery,customUpdate,customOptions);
statusArray.push(status);
db.close();
});
} catch (error) {console.log(error);}
}
if(statusArray){
console.log("success", statusArray.length);
resolve(statusArray);
} else {
console.log("error");
reject("reject because no statusArray");
}
});
}
updateServer().then(
function(statusArray){
return res.status(200).json({ "response": "success","statusArray":statusArray }).end();
}
).catch(
function(error){
return res.status(500).json({ "response": "error", }).end();
}
);
}
How to achieve that?
Any suggestions are always welcome!
I have tried to insert the value in db in my mocha test i am getting this error i tried few of the following ways but nothing work out.
var assert=require('chai').assert;
const user=require('../model/user')
i tried both way
describe('insertDataLasone',()=>{
it('should save the value ',(done)=>{
var User = new user({fname:'test'});
User.save().then(done=>{
done()
}).catch(done=>done())
})
})
describe('User', function() {
describe('#save()', function() {
// this.timeout(5000)
it('should save without error', function(done) {
var User5 = new user({fname:'test'});
User5.save(function(done) {
if (err) done(err);
else setTimeout(done,3000);
});
});
});
});
This error occurs when done() is not called in a test. Make sure you are calling done().
var assert = require('chai').assert;
const User = require('../model/user');
describe('insertDataLasone', () => {
it('should save the value ', done => {
var user = new User({ fname: 'test' });
user.save().then(() => {
done();
})
.catch(done); // mocha done accepts Error instance
});
});
or
var assert = require('chai').assert;
const User = require('../model/user');
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user5 = new User({ fname: 'test' });
user5.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
Read https://mochajs.org/#asynchronous-code carefully
I've been working a while on getting a test to work with Mocha and Passport. I tried a couple articles on here, but I can't get them to work.
Currently, I have installed supertest and I'm trying that.
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var app = require('../app');
//var request = require('supertest')//(app);
//var server = request.agent(app);
//var Strategy = require('passport-strategy');
var Strategy = require('passport-local').Strategy;
var m_ticket_data = require('../model/ticket');
var m_Kbase_data = require('../model/Kbase');
var m_KbaseScript_schema = require('../model/KbaseScript');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
chai.use(require('chai-passport-strategy'));
describe('Ticket', function() {
var user, info;
before(function(done) {
console.log("hello from strategy");
chai.passport.use( new Strategy(function(username, password, done){
console.log("hello from strategy2");
done(null, { id: '1234' }, { scope: 'read' });
}
))
.success(function(u, i) {
user = u;
info = i;
done();
})
.req(function(req) {
//req.headers.authorization = 'Bearer vF9dft4qmT';
})
.authenticate();
done();
});
it ('blankout the database', function(done){
m_ticket_data.remove({}, function(){
done();
});
});
it('looks for a blank from /ticket/all', function (done) {
chai.request('http://127.0.0.1:5000')
.get('/ticket/all')
.end(function (err, res) {
res.status.should.equal(200);
console.log(res.body);
//expect(res.body).to.deep.equal({});
done();
});
});
});
I can't create a temp user for testing, so I was thinking I was going to have to overwrite the authentication. However, I'm having a problem doing that. I found this npm (https://github.com/jaredhanson/chai-passport-strategy), and I'm trying this as the latest.
This is a test I created that works fine. I don't need to authenticate for it.
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../app');
var m_Kbase_data = require('../model/Kbase');
var m_KbaseScript_schema = require('../model/KbaseScript');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
describe('KBasefull', function() {
m_Kbase_data.collection.drop();
it('need to add a kbase article for testing /KBase', function (done) {
chai.request('http://127.0.0.1:5000')
.post('/kbase')
.send({Problem: "Problem", description: "Description", resolution: "Something to fix"})
.end(function(err, res){
res.should.have.status(200);
done();
});
});
}
I would like to know if I am missing anything with regard to sinon.js I have tried using sinon.stub().returns and yields but am unable to get the result. Any pointers would be helpful
I have a module which calls another module that returns the value from the DB
var users = require('/users');
module.exports.getProfileImage = function (req, res) {
var profile = {};
else {
users.findOne("email", req.session.user.email, function (err, user) {
if (err) {
res.status(400).send();
}
else if (!user) {
//return default image
}
else if (user) {
//Do some other logic here
}
});
};
I am using mocha as the testing framework and am also using sinon. The problem that I am facing is when i create a stub of users.findOne to return a value the control does not come to my else if (user) condition.
my unit test case is as follows
describe("Return image of user",function(){
var validRequest = null;
validRequest={
session:{
user:{
email:'testUser#test.com',
role:'Hiring Company'
}
}
};
it("Should return an image from the file if the user is present in db",function(done){
var findOneUserResponse ={
companyName:"xyz",
email:"xyz#abc.com"
};
var findOne = sinon.stub(mongoose.Model, "findOne");
findOne.callsArgWith(1,null,findOneUserResponse);
user.getProfileImage(validRequest,response);
var actualImage = response._getData();
findOne.restore();
done();
};
};
So I went through the sinon.js documentation http://sinonjs.org/docs/ and came across what I was missing
describe("Return image of user",function(){
var validRequest = null;
validRequest={
session:{
user:{
email:'testUser#test.com',
role:'Hiring Company'
}
}
};
it("Should return an image from the file if the user is present in db",function(done){
var findOneUserResponse ={
companyName:"xyz",
email:"xyz#abc.com"
};
var findOne = sinon.stub(mongoose.Model, "findOne",function(err,callback){
callback(null,findOneUserResponse);
)};
user.getProfileImage(validRequest,response);
var actualImage = response._getData();
findOne.restore();
done();
};
};
taking straight from this post:
This code never executes.
var Promise = require("bluebird");
Promise.promisifyAll(require("restify"));
var restify = require("restify");
var http = require('http');
const PORT=7070;
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
var client = restify.createJsonClientAsync({
url: 'http://127.0.0.1:7070'
});
client.get("/foo").spread(function(req, res, obj) {
console.log(obj);
});
I only put together this simple example to prove it to myself after my production code didn't work. I can hit localhost:7070 with curl and I get the expected results.
In a nutshell: I need to execute 3 GET calls to a server before I can create a POST and hence my need for promises.
Anyone can shed some insight? I can't imagine this being simpler.
UPDATE
Apparently i did not read the question correctly, here is a working example of 2 gets using a promisified restify json client. you would just do another spread in the body of the second spread for your post.
var promise = require('bluebird');
var restify = require('restify');
promise.promisifyAll(restify.JsonClient.prototype);
var client = restify.createJsonClient({
url: 'http://localhost:8080',
version: '*'
});
client.getAsync('/api/resource/1').spread(function(req, res, obj) {
console.log('result 1', obj);
return client.getAsync('/api/resource/2').spread(function(req, res, obj) {
console.log('result 2', obj);
});
});
As I stated in my comments, I would not promisify restify itself. Instead I would use either a handler whose body executes promise code or a chain of handlers (which can also have promises in the body). restify should only receive the request and execute the handler.
I will use modified versions of the basic example from the restify page to illustrate each.
Promise in the message body using knex.js which returns a promise
var knex = require('knex')(connectionConfig);
var restify = require('restify');
function promisePost(req, res, next) {
// get 1
knex.select('*')
.from('table1')
.where('id', '=', req.body.table1_id)
.then(function(result1) {
// get 2
return knex.select('*')
.from('table2')
.where('id', '=', req.body.table2_id)
.then(function(result2) {
return knex('table3').insert({
table1_value: result1.value,
table2_value: result2.value
})
.then(function(result3) {
res.send(result3);
return next();
});
});
});
}
var server = restify.createServer();
server.use(restify.bodyParser());
server.post('/myroute', promisePost);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
now with chained handlers
var knex = require('knex')(connectionConfig);
var restify = require('restify');
function get1(req, res, next) {
knex.select('*').from('table1')
.where('id', '=', req.body.table1_id)
.then(function(result1) {
res.locals.result1 = result1;
return next();
});
}
function get2(req, res, next) {
knex.select('*').from('table2')
.where('id', '=', req.body.table2_id)
.then(function(result2) {
res.locals.result2 = result2;
return next();
});
}
function post(req, res, next) {
knex('table3').insert({
table1_value: res.locals.result1,
table2_value: res.locals.result2
})
.then(function(result3) {
res.send(result3);
return next();
});
}
var server = restify.createServer();
server.use(restify.bodyParser());
server.post('/myroute', get1, get2, post);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});