Reputation: 15
I Am trying to perform a REST call in Mocha. I´tried to use the "request" framework to login at auth0. The REST call is correct, I tried the same data in Postman and got the correct answer.
Now I am trying to implement the call in our test, but this doesn't work. The methode doesn't open the call-back function and I'm not getting any answer from the server. In the backend-log I could see, that the call doesn't get through to the backend, and no login is performed. I tried several different methods from XMLHttpRequest to the request library.
Here the code I am using:
var should = require("should");
var assert = require('assert');
var request = require("request");
var authToken ='test';
var url = 'https://*****.eu.auth0.com/oauth/ro';
describe('auth0', function() {
describe('Login', function() {
it('should return authToken if user data is valid', function() {
//REST call to login
request.post({url:"https://********.eu.auth0.com/oauth/ro",
form: {
client_id:'*******************',
username:'*******************',
password:'*******************',
connection:'Username-Password-Authentication',
grant_type:'password',
scope:'openid'}},
function(err,httpResponse,body){
console.log('entered call-back function');
console.log(httpResponse);
});
console.log('accessToken: ' + authToken);
});
});
});
And here is what I get after running the code:
"C:\Program Files\nodejs\node.exe" "C:\Users\*******\AppData\Roaming\npm\node_modules\mocha\bin\_mocha" --ui bdd --reporter "C:\Program Files (x86)\JetBrains\WebStorm 2016.2.2\plugins\NodeJS\js\mocha-intellij\lib\mochaIntellijReporter.js" "C:\Users\*********\Desktop\********\Testing"
accessToken:test
Process finished with exit code 0
Hope you could help me.
Thank you!
Upvotes: 1
Views: 31
Reputation: 28837
You have to make the test run async
. You can add a argument in the mocha callback and then invoque it when the request is done:
it('should return authToken if user data is valid', function(done) {
//REST call to login
request.post({
url: "https://********.eu.auth0.com/oauth/ro",
form: {
client_id: '*******************',
username: '*******************',
password: '*******************',
connection: 'Username-Password-Authentication',
grant_type: 'password',
scope: 'openid'
}
},
function(err, httpResponse, body) {
console.log('entered call-back function');
console.log(httpResponse);
done(); // <-- here you tell mocha the async part is done
});
Upvotes: 1