2014-07-11 2 views
4

I가 다음 제공자 :

angular.module('MyApp').provider('MyDevice', function() { 

    var ngInjector = angular.injector(['ng']), 
     $window = ngInjector.get('$window'); 

    function isMobileDevice() { 
     return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/) 
      .test($window.navigator.userAgent || $window.navigator.vendor || $window.opera); 
    } 

    this.$get = function() { 
     return { 
      isDesktop: function() { 
       return !isMobileDevice(); 
      }, 
      isMobile: function() { 
       return isMobileDevice(); 
      } 
     }; 
    }; 

}); 

다음과 같은 테스트 사양 :

describe('MyDeviceProvider', function() { 

    var myDevice; 

    beforeEach(function() { 
     inject(['MyDevice', function (_myDevice_) { 
      myDevice = _myDevice_; 
     }]); 
    }); 

    it('Test #1', function() { 
     // Mock '$window.navigator.userAgent' to "desktop" 
     expect(myDevice.isDesktop()).toEqual(true); 
     expect(myDevice.isMobile()).toEqual(false); 
    }); 

    it('Test #2', function() { 
     // Mock '$window.navigator.userAgent' to "mobile" 
     expect(myDevice.isDesktop()).toEqual(false); 
     expect(myDevice.isMobile()).toEqual(true); 
    }); 

}); 

내 질문은, 어떻게 두 Test #1$window 조롱 않습니다되고 Test #2는 그래서 그들은 성공? 무수한 객체에 대해서는 $provide.valuespyOn으로 시도했지만, 내 테스트를 실행하려면 $window.navigator.userAgent의 값을 조롱하는 것처럼 보일 수 없습니다.

어떻게 해결할 수 있습니까?

P.S : 위의 코드는 문제의 데모로만 작동하며 응용 프로그램의 특별한 요구 사항으로 인해 공급자를 서비스로 변경할 수 없습니다.

답변

15

매우 조잡, 다음을 수행 할 수 :

describe('MyDeviceProvider', function() { 

    var myDevice, 
     $window, 
     navigator; 

    beforeEach(function() { 
     inject(['MyDevice', '$window', function (_myDevice_, _$window_) { 
      myDevice = _myDevice_; 
      $window = _$window_; 
     }]); 

     // Save the original navigator object 
     navigator = $window.navigator; 
    }); 

    afterEach(function() { 
     $window.navigator = navigator; 
    }); 

    it('Test #1', function() { 
     // Mock the entire navigator object to "desktop" 
     $window.navigator = { 
      userAgent: "desktop" // Use a real "desktop" user agent 
     }; 

     // Mock '$window.navigator.userAgent' to "desktop" 
     expect(myDevice.isDesktop()).toEqual(true); 
     expect(myDevice.isMobile()).toEqual(false); 
    }); 

    it('Test #2', function() { 
     // Mock the entire navigator object to "desktop" 
     $window.navigator = { 
      userAgent: "mobile" // Use a real "mobile" user agent 
     }; 
     // Mock '$window.navigator.userAgent' to "mobile" 
     expect(myDevice.isDesktop()).toEqual(false); 
     expect(myDevice.isMobile()).toEqual(true); 
    }); 

}); 

너무 다른 브라우저를 흉내 다른 모의 객체를 테스트해야합니다.

+0

달콤한 대답 thx :) – danday74

+0

당신은 나를 많이 도왔습니다 :) – John

+1

'주사 ([...])를 둘러싼 기능은 초자연적이라고 믿습니다. –