在Mocha使用node.js执行REST调用

我正尝试在Mocha执行REST调用。 我试图使用“请求”框架来loginauth0。 REST调用是正确的,我在Postman中尝试了相同的数据,并得到了正确的答案。

现在我正在尝试在我们的testing中实现这个调用,但是这不起作用。 方法不打开callback函数,我没有从服务器得到任何答案。 在后台日志中我可以看到,这个调用没有通过后端,也没有进行login。 我尝试了XMLHttpRequest到请求库的几种不同的方法。

这里我正在使用的代码:

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); }); }); }); 

这是我运行代码后得到的结果:

 "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 

希望你能帮助我。

谢谢!

您必须使testing运行async 。 您可以在mochacallback中添加一个参数,然后在请求完成时对其进行invoque:

 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 });