【问题标题】:Jasmine does not Resolve Angular PromiseJasmine 没有解决 Angular Promise
【发布时间】:2016-11-23 00:26:05
【问题描述】:

我是 Jasmine 的新手。我试图让我的工厂承诺得到解决,但似乎从来没有。

这是我的工厂,它将返回公司列表

angular.module('commercial.factories').factory('companyFactory', companyFactory);

function companyFactory($http, $location, sessionStorage, config) {
    function getCompanies() {
        //call service and include company identifier in the service url
        return $http.get(wunUtils.constants.serviceBaseUrl + 'myCompanyService.svc/companies')
            .then(function(response) {
                return response.data;
            }, function(err){
                console.log(err);
            });
    }
});

和我的规范

describe('company', function() {
beforeEach(module('mockedCommercial'));

var $httpBackend, companyFactory, $rootScope

beforeEach(function() {

    inject(function(_$httpBackend_, _$rootScope_, _companyFactory_) {
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        companyFactory = _companyFactory_;
    });
})


it('should return available languages asynchronously', function() {


    $httpBackend.expectGET(/https:\/\/myDomain.com\/myCompanyService.svc\/companies+/)

        .respond(function(method, url, data, headers, params) {

            var response = {
                "data": [{
                    "address1": "Portsmouth",
                    "address2": null,
                    "city": "Portsmouth",
                    "contactEmail": "mocks@mocks.com",
                    "contactFirstName": "Mock",
                    "contactLastName": "Data",
                    "contactPhone": null,
                    "contactTitle": "Mr",
                    "country": "UK",
                    "fax": null,
                    "identifier": "c1xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                    "location": "Portsmouth, UK",
                    "name": "Mock Company 1",
                    "phone": null,
                    "state": "Hampshire",
                    "zipCode": "PO19 3 EN"
                }, {
                    "address1": "Portsmouth",
                    "address2": null,
                    "city": "Portsmouth",
                    "contactEmail": "mocks@mocks.com",
                    "contactFirstName": "Test",
                    "contactLastName": "Test",
                    "contactPhone": null,
                    "contactTitle": "Mrs",
                    "country": "UK",
                    "fax": null,
                    "identifier": "c2xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                    "location": "Portsmouth, UK",
                    "name": "Mock Company 2",
                    "phone": null,
                    "state": "Hampshire",
                    "zipCode": "Po9 3EN"
                }],
                "total": 2
            }

        });


    //--------------------------

    $rootScope.$digest();

    companyFactory.GetCompanies().then(function(result) {
        expect(result.hasOwnProperty('total')).toBe(true);
    })
});
});

如您所见,我正在使用 $rootScope.$digest 运行承诺,但我的期望从未达到,因此测试总是通过。

我已经阅读了大量关于此的不同帖子,他们都说这应该有效。我在这里做错了什么还是我错过了一些步骤?

已编辑 - 简化方法

所以在看了更多帖子后,我稍微简化了我的问题

这是我的新控制器调用...

        $scope.companies = [];
    var GetCompanies = function(options) {
        companyFactory.GetCompanies().then(function(response) {
            options.success(response);
            $scope.companies = response
        });
    }
$scope.GetCompanies = GetCompanies

我的工厂...

function getCompanies() {
    //call service and include company identifier in the service url
    return $http.get(wunUtils.constants.serviceBaseUrl + 'CompanyService.svc/companies')
        .then(function(response) {
            return response.data;
        }, function(err){
            console.log(err);
        });
}
    var service = {
    AddCompany: addCompany,
    GetCompany: getCompany,
    GetCompanies: getCompanies,
    GetUserCompanyFleets: getUserCompanyFleets,
    EditCompany: editCompany
};

还有我的新规范

describe('company', function() {
beforeEach(module('mockedCommercial'));

var $httpBackend, companyFactory, $rootScope, createController, scope

beforeEach(function() {

    inject(function($controller, _$httpBackend_, _$rootScope_, _companyFactory_) {
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        scope = _$rootScope_.$new();
        companyFactory = _companyFactory_;
        createController = function() {
            return $controller('ManageCompaniesController', {
                '$scope': scope
            });
        };
    });
})


it('should return available languages asynchronously', function(done) {

    $httpBackend.whenGET(/https:\/\/myDomain.com\/V3_Fleet\/CompanyService.svc\/companies+/)

        .respond(function(method, url, data, headers, params) {
                return [{ 'id': 1 }];
            }
        });

    //--------------------------
    var dummy = [{ 'id': 1 }];

    createController();

    scope.GetCompanies()

    $httpBackend.flush()


    expect(scope.companies).toEqual(dummy)


    scope.$digest(); done()

});

});

【问题讨论】:

  • 你的问题解决了吗?
  • 您的companyFactory 中存在语法问题。您只是将 GetCompanies 声明为本地函数,而不是返回对象的方法。
  • 你不需要return 来自it 回调的承诺吗?
  • 请检查我的编辑
  • 尝试在$httpBackend.flush() 之后调用scope.$apply() 来处理在angular 中排队的微任务。

标签: javascript angularjs jasmine karma-jasmine


【解决方案1】:

在评估测试预期之前尝试使用$httpBackend.flush()。

这是 angular 推荐的方法。更多详情和示例,您可以查看documentation here。

【讨论】:

  • 嘿@boyomarinov 我已经尝试过了,但仍然无法解决。请查看我的问题的编辑
【解决方案2】:

在测试异步代码时有两种选择。

1。对所有内容使用同步模拟

这包括:

  • 模拟$httpBackend
  • 使用$timeout.flush()
  • 使用$interval.flush()
  • 使用scope.$apply() 处理剩余的promise

在所有这些之后,您仍然不能完全确定所有待处理的任务都已处理,尽管在 99.9% 的情况下这已经足够了。

2。使您的测试异步

在这里,您必须确保每个异步控制器方法都返回一个 Promise,即使返回的 Promise 没有在应用程序中使用。它们将用于测试。

Jasmine 使异步测试变得相当困难,但并非不可能。您将不得不使用done callback,并对每个异步块进行编码,例如:

it('should...', function(done) {
    $q.when().then(function() {
        return $controller.GetSomething();
    }).then(function() {
        expect(scope.companies).toEqual(dummy);
    }).then(done, done.fail);
});

Mocha handles proper asynchronous functions 所以你可以不用done 写:

it('should...', function() {
    return $q.when().then(function() {
        return $controller.GetSomething();
    }).then(function() {
        expect(scope.companies).toEqual(dummy);
    });
});

如果您有工具集,甚至可以使用async-await:

it('should...', async () => {
    await $controller.GetSomething();
    expect(scope.companies).toEqual(dummy);
});

【讨论】:

    【解决方案3】:

    因此,经过大量阅读,我通过简化所有内容找到了答案。我认为我的问题来自混合 $httpBackend.flush() 和 done() 函数

    似乎发生的事情是 done() 函数触发了它自己的摘要,因此在尝试使用 flush() 函数时会发生冲突。

    这是我的工作工厂。它与我原来的 purly 有点不同,因为这是一个更简单的函数(出错的事情更少)

            function getUser(userId) {
            //call service and include user identifier in the service url
            return $http.get(wunUtils.constants.serviceBaseUrl + 'myService.svc/fleetusers/' + userId)
                .then(function(response) {
                    return response.data;
                });
             }
    
            var service = {
            GetMe: getMe,
            GetUser: getUser,
            AddUser: addUser,
            EditUser: editUser,
            ActivateUser: activateUser
        };
    

    这是我的简化规范,称为 $httpBackend.Flush()

    describe('Testing httpBackend', function() {
    
    var $httpBackend;
    
    beforeEach(module('mockedCommercial'));
    
    
    beforeEach(inject(function(_$httpBackend_) {
        $httpBackend = _$httpBackend_;
    }))
    
    it('should behave...', function() {
    
        inject(function(userFactory, $rootScope) {
    
            var mockData = [];
    
            $httpBackend.expectGET(wunUtils.constants.serviceBaseUrl + 'FleetUserService.svc/fleetusers/10').respond(mockData);
    
            var promise = userFactory.GetUser(10);
    
            $httpBackend.flush();
    
            promise.then(function(result) {
                expect(result).toEqual(mockData);
            });
    
            });
    
    });
    });
    

    编辑

    还应注意,在测试 HTTPBackend 时,该测试仅在使用 expectGET 和 expectPOST 时才有效,而不是 whenGET 和 whenPOST。

    据我所知,whenGet 用于模拟数据,而 expectGet 用于测试模拟

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2017-11-16
      • 1970-01-01
      • 2016-06-01
      • 2019-02-18
      • 2018-08-19
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      相关资源
      最近更新 更多