1+ describe ( '$q decorator' , function ( ) {
2+ beforeEach ( module ( 'angular-data.DS' ) ) ;
3+
4+ it ( 'should decorate $q' , inject ( function ( $q ) {
5+ assert . isFunction ( $q . promisify ) ;
6+ } ) ) ;
7+
8+ it ( 'should resolve with a cb' , inject ( function ( $q , $rootScope ) {
9+ var resolveValue = { } ;
10+ var resolveCb = function ( cb ) {
11+ cb ( null , resolveValue ) ;
12+ } ;
13+ var resolveSpy = sinon . spy ( ) ;
14+
15+ $q . promisify ( resolveCb ) ( ) . then ( resolveSpy ) ;
16+ $rootScope . $digest ( ) ;
17+
18+ assert ( resolveSpy . calledWith ( resolveValue ) ) ;
19+ } ) ) ;
20+
21+ it ( 'should reject with a cb' , inject ( function ( $q , $rootScope ) {
22+ var rejectValue = { } ;
23+ var rejectCb = function ( cb ) {
24+ cb ( rejectValue ) ;
25+ } ;
26+ var rejectSpy = sinon . spy ( ) ;
27+
28+ $q . promisify ( rejectCb ) ( ) . then ( null , rejectSpy ) ;
29+ $rootScope . $digest ( ) ;
30+
31+ assert ( rejectSpy . calledWith ( rejectValue ) ) ;
32+ } ) ) ;
33+
34+ it ( 'should resolve with a promise' , inject ( function ( $q , $rootScope ) {
35+ var resolveValue = { } ;
36+ var resolveCb = function ( cb ) {
37+ return $q . when ( resolveValue ) ;
38+ } ;
39+ var resolveSpy = sinon . spy ( ) ;
40+
41+ $q . promisify ( resolveCb ) ( ) . then ( resolveSpy ) ;
42+ $rootScope . $digest ( ) ;
43+
44+ assert ( resolveSpy . calledWith ( resolveValue ) ) ;
45+ } ) ) ;
46+
47+ it ( 'should reject with a promise' , inject ( function ( $q , $rootScope ) {
48+ var rejectValue = { } ;
49+ var rejectCb = function ( cb ) {
50+ return $q . reject ( rejectValue ) ;
51+ } ;
52+ var rejectSpy = sinon . spy ( ) ;
53+
54+ $q . promisify ( rejectCb ) ( ) . then ( null , rejectSpy ) ;
55+ $rootScope . $digest ( ) ;
56+
57+ assert ( rejectSpy . calledWith ( rejectValue ) ) ;
58+ } ) ) ;
59+
60+ //Typically, functions that return a promise will be wrapped with a $q.when, meaning if you were to return nothing, it would execute straight away
61+ //This would mean the cb style would not work at all, as any developer that uses cb would have the function immediately resolve
62+ //This just ensures that doesn't ever happen
63+ it ( 'should not resolve or reject if return value is not a promise' , inject ( function ( $q , $rootScope ) {
64+ var resolve ;
65+ var cb = function ( next ) {
66+ resolve = next ;
67+ return true ;
68+ }
69+ var spy = sinon . spy ( ) ;
70+
71+ $q . promisify ( cb ) ( ) . finally ( spy ) ;
72+ $rootScope . $digest ( ) ;
73+
74+ assert ( ! spy . called ) ;
75+
76+ resolve ( ) ;
77+ $rootScope . $digest ( ) ;
78+
79+ assert ( spy . called ) ;
80+ } ) ) ;
81+ } )
0 commit comments