我正在尝试使用 Karma
在 Jasmine
测试中执行简单的 HTTP post。我有代码并且它可以工作,因为我使用 Chrome 应用 Postman
并已成功检索用户凭据。
所以这一定是我的单元测试
。我做错了什么?
signInSpec.js:
describe('Service: AuthFactory',function(){
beforeEach(function () {
module('ui.router');
module('users');
});
var AuthFactory, httpBackend;
beforeEach(function($httpBackend, _AuthFactory_) {
httpBackend = $httpBackend;
AuthFactory = _AuthFactory_;
});
it('should return POST', function(done) {
AuthFactory.signIn({inputType: {user: "admin"}, credInput: {password: "pass123"}});
httpBackend.when('POST','http://localhost:3000/api/AuthFactoryServ/signIn')
.respond (200, {});
httpBackend.flush(); // to return the response
}, 20000);
});
和AuthFactory.js:
angular.module('users').factory('AuthFactory', ['$http', function($http) {
var AuthFactory = {};
AuthFactory.signIn = function(data) {
return $http.post('http://localhost:3000/api/AuthFactoryServ/signIn', data);
};
AuthFactory.signOut = function(data) {
return $http.post('http://localhost:3000/api/AuthFactoryServ/signOut', data);
};
return AuthFactory;
}]);
错误:
PhantomJS 1.9.8 (Windows 7 0.0.0) Service: Authentication should return POST F
AILED
Error: Timeout - Async callback was not invoked within timeout specifi
ed by jasmine.DEFAULT_TIMEOUT_INTERVAL.
TypeError: 'undefined' is not an object (evaluating 'AuthFactory.signIn')
at C:/maink/client/tests/signInSpec.js:1
最佳答案
你需要模拟实际的ajax调用,这样它就会调用你的假的
it('should return POST', function(done) {
// dont worry about calls to assets
httpBackend.when ('POST','http://localhost:3000/api/AuthFactoryServ/signIn')
.respond (200, {});
AuthFactory.signIn({inputType: {user: "admin"}, credInput: {password: "pass123"}});
httpBackend.flush(); // to return the response
关于javascript - AngularJS - HTTP POST 异步回调未在指定的超时内调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34681410/