我正在尝试在Mocha中执行REST调用。我想使用“请求”框架登录auth0。 REST调用是正确的,我在Postman中尝试了相同的数据并得到了正确的答案。
现在我正在尝试在我们的测试中实现调用,但这不起作用。 方法不会打开回调函数,我也没有从服务器得到任何答案。在后端日志中我可以看到,调用没有通过后端,也没有执行登录。 我尝试了从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
希望你能帮助我。
谢谢!
答案 0 :(得分:1)
您必须进行测试async
。您可以在mocha回调中添加一个参数,然后在请求完成时对其进行调用:
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
});