javascript - AngularJS - HTTP POST 异步回调未在指定的超时内调用

标签 javascript angularjs unit-testing jasmine

我正在尝试使用 KarmaJasmine 测试中执行简单的 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/

相关文章:

javascript - 在 put 方法之前从作用域获取数据

python - 在 python 中组合断言

c# - 为什么每个 [TestMethod] 都会多次调用 [TestClass] 的构造函数?

javascript - 如何通过 VIsJS 网络中的箭头方向更改节点位置

jquery - AngularJS:$timeout CSS 修复程序不会在页面加载时运行

angularjs - Protractor - 作为移动设备运行特定测试

python - 访问了模拟实例上的断言属性

javascript - 减少代码 - 附加 svg 图像的重复代码

javascript - 谷歌驱动器 API 超出用户速率限制

javascript - 如何使用javascript获取h1标签的高度?