我正在尝试使用 Jasmine
返回关于单元测试的简单 HTTP 帖子,但它似乎不起作用。该应用程序在网络上运行良好。我测试了几个孤立的功能。但这行不通。
describe('Service: Auth',function(){
beforeEach(function () {
module('ui.router');
module('main');
module('users');
});
var AuthFactory, httpBackend;
beforeEach(inject(function($httpBackend, _AuthFactory_) {
httpBackend = $httpBackend;
AuthFactory = _AuthFactory_;
}));
it('should return POST', function() {
AuthFactory.signIn({inputUser: {username: "admin"}, passInput: {password: "adminpass"}}).then(
function(result) {
console.log('======== SUCCESS ========');
console.log(result);
},
function(err) {
console.log('======== ERROR ========');
console.log(err);
},
function(progress) {
console.log('======== PROGRESS ========');
console.log(progress);
}
);
console.log('HTTP call finished.');
expect(1).toBe(1);
});
});
这是工厂:
angular.module('users').factory('AuthFactory', ['$http', function($http) {
var AuthFactory = {};
AuthFactory.signIn = function(data) {
return $http.post('http://127.0.0.1:3000/api/AuthFactoryServ/signIn', data);
};
AuthFactory.signOut = function(data) {
return $http.post('http://127.0.0.1:3000/api/AuthFactoryServ/signOut', data);
};
return AuthFactory;
}]);
这是我得到的:
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 0 of 1 SUCCESS (0 s
LOG: Object{$$state: Object{status: 0}, success: function (fn)
{ ... }, error: function (fn) { ... }}
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 0 of 1 SUCCESS (0 s
LOG: 'HTTP call finished.'
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 0 of 1 SUCCESS (0 s
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 SUCCESS (0 s
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 SUCCESS (0 secs / 0.022 secs)
我已经通过 Postman 测试了 HTTP 调用,它成功返回了数据。那么...我做错了什么?
谢谢。
最佳答案
AuthFactory.signIn
是异步的并返回一个 promise - 您的测试函数在 promise 得到解决之前完成。
你需要告诉 Jasmine 它应该 wait for the asynchronous test to complete :
it('should return POST', function(done) {
var result = AuthFactory.signIn({inputUser: {username: "admin"}, passInput: {password: "adminpass"}}).then(
function(result) {
console.log('======== SUCCESS ========');
console.log(result);
},
function(err) {
console.log('======== ERROR ========');
console.log(err);
},
function(progress) {
console.log('======== PROGRESS ========');
console.log(progress);
}
);
result.then(function(){
console.log('HTTP call finished.');
expect(1).toBe(1);
}).finally(done); //here we hook Jasmine callback to promise chain
});
关于JavaScript - AngularJS promise 不返回任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663206/