File tree 2 files changed +71
-0
lines changed
2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -160,6 +160,37 @@ function createDebug(namespace) {
160
160
return section ;
161
161
} ;
162
162
163
+ debug . time = function ( ) {
164
+ var args = [ ] . slice . call ( arguments ) ;
165
+ if ( args . length < 2 ) {
166
+ throw new Error ( 'debug.time() takes at least a debug string and a function' ) ;
167
+ }
168
+
169
+ var fn = args . pop ( ) ;
170
+ if ( typeof fn !== 'function' ) {
171
+ throw new Error ( 'the last argument to debug.time() must be a function' ) ;
172
+ }
173
+
174
+ var isPromise = false ;
175
+ var section = debug . begin . apply ( debug , args ) ;
176
+ try {
177
+ var result = fn ( ) ;
178
+
179
+ if ( typeof Promise === 'function' && result instanceof Promise ) { // eslint-disable-line no-undef
180
+ isPromise = true ;
181
+ result . then ( function ( ) {
182
+ section . end ( ) ;
183
+ } ) ;
184
+ }
185
+
186
+ return result ;
187
+ } finally {
188
+ if ( ! isPromise ) {
189
+ section . end ( ) ;
190
+ }
191
+ }
192
+ } ;
193
+
163
194
// env-specific initialization logic for debug instances
164
195
if ( 'function' === typeof exports . init ) {
165
196
exports . init ( debug ) ;
Original file line number Diff line number Diff line change @@ -82,6 +82,46 @@ describe('debug', function () {
82
82
83
83
expect ( log . log ) . to . have . been . calledThrice ;
84
84
} ) ;
85
+
86
+ it ( 'times a critical function' , function ( ) {
87
+ log . log = sinon . spy ( ) ;
88
+
89
+ var result = log . time ( 'a critical function' , function ( ) {
90
+ log ( 'hello from inside' ) ;
91
+ return 1234 ;
92
+ } ) ;
93
+
94
+ expect ( result ) . to . equal ( 1234 ) ;
95
+ expect ( log . log ) . to . have . been . calledThrice ;
96
+ } ) ;
97
+
98
+ it ( 'should throw if there aren\'t enough arguments' , function ( ) {
99
+ log . log = sinon . stub ( ) ;
100
+
101
+ expect ( function ( ) {
102
+ log . time ( ) ;
103
+ } ) . to . throw ( 'debug.time() takes at least a debug string and a function' ) ;
104
+
105
+ expect ( function ( ) {
106
+ log . time ( 'hello' ) ;
107
+ } ) . to . throw ( 'debug.time() takes at least a debug string and a function' ) ;
108
+
109
+ expect ( function ( ) {
110
+ log . time ( function ( ) { } ) ;
111
+ } ) . to . throw ( 'debug.time() takes at least a debug string and a function' ) ;
112
+ } ) ;
113
+
114
+ it ( 'should throw if last argument isn\'t a function' , function ( ) {
115
+ log . log = sinon . stub ( ) ;
116
+
117
+ expect ( function ( ) {
118
+ log . time ( 'hello' , 1234 ) ;
119
+ } ) . to . throw ( 'the last argument to debug.time() must be a function' ) ;
120
+
121
+ expect ( function ( ) {
122
+ log . time ( 'hello' , function ( ) { } , 1235 ) ;
123
+ } ) . to . throw ( 'the last argument to debug.time() must be a function' ) ;
124
+ } ) ;
85
125
} ) ;
86
126
} ) ;
87
127
} ) ;
You can’t perform that action at this time.
0 commit comments