Jasmine测试处理承诺和$ q.when

时间:2016-12-26 15:22:41

标签: angularjs jasmine

这是localeDataService来检索一些数据。

function getapplicableitems() {
    if (profile.region === 'ASIA') {
        return otherDataService.getOtherData()
            .then(function(data) {
                return data;
            });
        }
    return $q.when(false);
}

这些是我的茉莉花测试。

describe('Locale Data Service Tests:',
function() {

    var sut,
        profile = {},
        otherDataServiceMock = {},
        $q;

    beforeEach(module(function($provide) {
        otherDataServiceMock = {
            getOtherData: function() {}
        };

        spyOn(otherDataServiceMock, 'getOtherData')
            .and.callFake(function() {
                var deferred = $q.defer();
                deferred.resolve('Remote call result');
                return deferred.promise;
            });

        $provide.value('profile', profile);
        $provide.value('otherDataService', otherDataServiceMock);
    }));

    beforeEach(inject(function(_localeDataService_, _$q_) {
        $q = _$q_;
        sut = _localeDataService_;
    }));

    it('should not call if region is NOT ASIA', function() {
            profile.region = 'ZZZZ';

            spyOn(otherDataServiceMock, 'getOtherData').andReturn($q.when(false));

            sut.getOtherData();

          expect(otherDataServiceMock.getOtherData).toEqual($q.when(false));

    });

    it('should call for ASIA', function() {
            profile.region = 'ASIA';

            sut.getOtherData();

            expect(otherDataServiceMock.getOtherData).toHaveBeenCalled();
        });
});

我无法得到这个"不应该打电话,如果地区不是亚洲"测试工作。我是茉莉花/单元测试的新手。请帮忙。

1 个答案:

答案 0 :(得分:0)

这是我解决它的方式。没有必要调用otherDataServiceMock,因为当区域是ZZZZ时它不会被使用。

it('should not call if region is NOT ASIA', function() {
        profile.region = 'ZZZZ';
        var noChange = true;

        sut.getOtherData().then(function(){
           noChange = false;
        });

      expect(noChange).toBeTruthy()

});