Unable to pass parameter from the api request to outside - mocha.js

The code below is a simple mocha test where I am trying to pass the value of the variable my_token so that I can use in different tests. Tried all the possibilities but its not working. Not sure what I am doing wrong!
var supertest = require('supertest'),
api = supertest('www.xyz.com');
var my_token = 'DID NOT WORK';
describe('get collars list', function(done) {
before(function(done) {
api.post('/api/v2/auth')
.send({username:"SP",password:"**"})
.set('Content-Type', 'application/json')
.expect(200)
.end(function (err, res) {
my_token = "worked"
done();
});
console.log ('passing value to the test : '+ my_token );
});
it('should login', function(done) {
console.log (' token passed to test : ' + my_token);
});
});

You do not need done in a test case that doesn't involve asynchronous operation.
This should work.
var supertest = require("supertest"),
api = supertest("www.xyz.com");
var my_token = "DID NOT WORK";
describe("get collars list", function(done) {
before(function(done) {
api
.post("/api/v2/auth")
.send({ username: "SP", password: "**" })
.set("Content-Type", "application/json")
.expect(200)
.end(function(err, res) {
my_token = "worked";
done();
});
console.log("passing value to the test : " + my_token);
});
it("should login", function() {
console.log(" token passed to test : " + my_token);
});
});

Related

Not able to use alias across tests in Cypress

I am trying to create a framework for API tests using cypress and I am facing an issue accessing the data between tests using an alias. Is there something that I am missing?
custom.js
Cypress.Commands.add('getResource', function (uri) {
cy.request({
url: uri,
method: 'GET'
}).then(function (response) {
return cy.wrap(response);
});
});
test.js
exports.__esModule = true;
context('requests', function () {
it('validate get call response', function () {
let re = cy.getResource('https://reqres.in/api/users?page=2','resp')
re.then(function (response) {
cy.wrap(response.body).as('respbody');
cy.wrap(response.status).as('respstatus');
//cy.log(JSON.stringify(response.body));
});
});
it('Tests test', function () {
cy.wait('#respbody').then((body) => {
console.log(JSON.stringify(body));
});
});
});
cypress version - 8.2.0
By design cypress cleans up aliases after each test. So you can do something like this cypress recipe
Your getResource custom command is taking just one parameter, hence we are passing just one papameter.
exports.__esModule = true;
let responseBody;
let responseStatus;
context('requests', () => {
before(() => {
cy.getResource('https://reqres.in/api/users?page=2')
.then(function(response) {
responseBody = response.body
responseStatus = response.status
})
})
beforeEach(() => {
cy.wrap(responseBody).as('responseBody')
cy.wrap(responseStatus).as('responseStatus')
})
it('Get Response status', function() {
cy.wait('#responseStatus').then((responseStatus) => {
console.log(responseStatus)
})
})
it('Get Response Body', function() {
cy.wait('#responseBody').then((responseBody) => {
console.log(JSON.stringify(responseBody))
})
})
})

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves

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

aws lambda expression with alexa skills

I am able to invoke the lambda expression using Alexa sdk, but unable to call the external service from the lambda expression. I am not getting any error or response. I'm not sure what's wrong with this.
While testing the lambda expression I'm only able to get the logs until 'Do the POST call', not after that. That means something wrong in https.request.
The same logic tested with node.js is able to get the response correctly. Any thoughts?
var https = require('https');
var responseString = '';
var postheaders = {
'Content-Type' : 'application/json'//,
//'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};
var optionspost = {
host : '{host name}',
port : 443,
path : '{path name}',
method : 'POST',
headers : postheaders
};
console.info('Options prepared:');
//console.info(optionspost);
console.info('Do the POST call');
// do the POST call
var reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('POST result:\n');
process.stdout.write(d);
responseString += d;
console.info('\n\nPOST completed');
});
res.on('error', function(e) {
console.error('error');
console.error(e);
});
res.on('end', function () {
console.info('end');
var responseObject = JSON.parse(responseString);
if (responseObject.error) {
console.info("NOAA error: " + responseObject.error.message);
} else {
console.info(responseString);
}
});
}).on('error', function(e) {
console.error('Communications err' + e);
console.error(e);
});
reqPost.end();
reqPost.on('error', function(e) {
console.error(e);
}).on('error', function (e) {
console.log("Communications error: " + e.message);
});

Does Vue.JS work with AJAX http calls?

I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.

Is my express post request is correct?

I'm trying to understand how Post Request works with express. I my case I would like to be able to update an web API call (is this the right term ?) with Google Analytics API. Most of the examples I found here or there are about handling post message or sign in operation.
Following this question here is what I have understand. On the front-end, using axios here is what I need to pass :
axios.post("http://localhost:3000/endpoints", my_parameters)
I can easily send this on the server side with react/redux. however on the server side, I'm kind of lost. I've got the following API call :
var key = require('./client_id.json')
var jwtClient = ...
var VIEW_ID = "ga:80820965";
var authorize = function( cb ) {
jwtClient.authorize(function(err) {
if (err) {
console.log(err);
return;
} else {
if ( typeof cb === "function") {
cb();
}
}
});
}
var queryData = function(req, res) {
authorize(function() {
analytics.data.ga.get({
'auth': jwtClient,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err);
return;
}
res.send(response);
});
});
}
module.exports = {
queryData
};
and my express server set-up :
const app = express();
app.use('/', express.static('public'));
app.use('/', express.static('src'));
var ga = require('./src/apicall/gadata');
app.listen(process.env.PORT || 3000);
app.set('views', './src/views');
app.set('view engine', 'ejs');
app.use('/gadata', ga.queryData);
so after I've dispatched my axios.post, how do I handle it in my server.babel.js file ?
I guess I need to use a structure like this :
router.get('/newUser', (req, res) => {
TestUser.save({
name: 'sawyer',
email: 'sawyer#test.com'
}).then((result) => {
console.log('Saved!')
res.send(result)
})
})
but I don't really know how I should refactor it to pass my parameters so I can actually update my google analytics api call ?
thanks.

Resources