我以为我设置此Promise以尝试使用supertest执行RESTful服务的登录POST请求。但是,它对我不起作用。
以下是代码:
'use strict';
/*
* loginRequest.js
*
* Perform a basic login using supplied values. Only tests for Response Code 200
*/
var base64_encode = require('Base64').btoa
, request = require('supertest')
, VerifyUrl = require('./VerifyUrl');
module.exports = loginRequest;
/**
* Perform a basic login and returns a Promise. It resolves with the response or rejects with the error.
*
* @param username {string} The username.
* @param password {string} The password.
* @param url {string} The url under test. If not supplied, assumes 'http://localhost:9000/'
* @returns {Promise} The Promise container of the login request which resolves with the POST response or rejects with the error.
*/
function loginRequest(username, password, url) {
return new Promise(function (resolve, reject) {
url = VerifyUrl(url); // Provides a default url if non is supplied, ensures a trailing '/'.
var authorization = "Basic " + base64_encode(username + ':' + password); // Yes, I know, not secure. The app isn't yet production ready.
console.log("creds = " + username + ':' + password);
console.log("auth = " + authorization);
request(url)
.post('api/users/login')
.set('authorization', authorization)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.expect(function() {console.log("Made the expectation.")})
.end(function (err, res) {
console.log("Reached the login .end method.");
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
这个输出是:
creds = autoTest1465828536379:4ut0T3st
auth = Basic YXV0b1Rlc3QxNDY1ODI4NTM2Mzc5OjR1dDBUM3N0
当我通过调试器运行它时,每个request
方法都有断点,它在.set处停止,但不运行.expect
或.end
方法。我缺少什么或不理解?
其他信息。从spec脚本中,我使用上面的代码如下:
var login = require('loginRequest');
var username = 'autoTest' + Date.now();
var password = '4ut0T3st';
login(username, password, 'http://localhost:9000')
.then(function(loginResponse) {
// do stuff with the response
})
.catch(function(err) {
// do stuff with the err
});
但它永远不会达到此次通话的.then
或.catch
。 (输出如上所述。