无法从角度服务中获得承诺

时间:2015-10-25 08:43:34

标签: angularjs jasmine promise karma-jasmine

我正在尝试模拟我正在使用的服务,并且应该返回一个承诺,正在调用模拟服务,但我无法将结果发送到我的测试中。

要测试的服务功能:

function getDevices() {
            console.log('getDevices');
            return servicesUtils.doGetByDefaultTimeInterval('devices')
                .then(getDevicesComplete);

            function getDevicesComplete(data) {
                console.log('getDevicesComplete');
                var devices = data.data.result;
                return devices;
            }
        }

我的测试是:

describe('devicesService tests', function () {
    var devicesService;
    var servicesUtils, $q, $rootScope;

    beforeEach(function () {
        servicesUtils = {};

        module('app.core', function ($provide) {
            servicesUtils = specHelper.mockServiceUtils($provide, $q, $rootScope);
        });

        inject(function (_devicesService_, _$q_, _$rootScope_) {
            devicesService = _devicesService_;
            $q = _$q_;
            $rootScope = _$rootScope_.$new();
        });
    });

    it('getting device list', function () {
        console.log('getting device list');
        devicesService.getDevices().then(function (result) {
            console.log(result);
            expect(result).toBeDefined();
        });    
    });
});

模拟文件:

function mockServiceUtils($provide, $q) {
        var servicesUtils = {};
        servicesUtils.doGetByDefaultTimeInterval = jasmine.createSpy().and.callFake(function() {
            var deferred = $q.defer();
            deferred.resolve('Remote call result');
            $rootScope.$digest();
            return deferred.promise;
        });

        $provide.value('servicesUtils', servicesUtils);

        return servicesUtils;
    }

1 个答案:

答案 0 :(得分:1)

您的代码太复杂了。

假设您要测试使用其他服务devicesService的服务servicesUtils,该服务具有返回承诺的方法。 我们假设devicesService的责任是调用servicesUtils并转换其结果。

我将如何做到这一点:

describe('devicesService', function() {

  var devicesService, servicesUtils;

  beforeEach(module('app.core'));
  beforeEach(inject(function(_devicesService_, _servicesUtils_) {
    devicesService = _devicesService_;
    servicesUtils = _servicesUtils_;
  }));

  it('should get devices', inject(function($q, $rootScope) {
    spyOn(servicesUtils, 'doGetByDefaultTimeInterval').and.returnValue($q.when('Remote call result'));

    var actualResult;
    devicesService.getDevices().then(function(result) {
      actualResult = result;
    });
    $rootScope.$apply();

    expect(actualResult).toEqual('The transformed Remote call result');
  }));
});