1+ import { Observable } from "tns-core-modules/data/observable" ;
2+ import { assert } from "chai" ;
3+
4+ describe ( "observable" , ( ) => {
5+ describe ( "once" , ( ) => {
6+
7+ let observable : Observable ;
8+ let handler : ( ) => void ;
9+ let callCount : number = 0 ;
10+
11+ beforeEach ( "create handlers" , ( ) => {
12+ handler = function ( ) {
13+ callCount ++ ;
14+ }
15+ observable = new Observable ( ) ;
16+ observable . once ( "test" , handler ) ;
17+ } ) ;
18+ afterEach ( "reset handlers" , ( ) => {
19+ callCount = 0 ;
20+ handler = null ;
21+ observable = null ;
22+ } ) ;
23+
24+ function notify ( ) {
25+ observable . notify ( { eventName : "test" , object : observable } ) ;
26+ }
27+ function notifyWrong ( ) {
28+ observable . notify ( { eventName : "test2" , object : observable } ) ;
29+ }
30+
31+ it ( "fires just once" , ( ) => {
32+ notify ( ) ;
33+ notify ( ) ;
34+ assert . equal ( callCount , 1 , "Expected the handler to be called exactly once" ) ;
35+ } ) ;
36+ it ( "does not fire for other events" , ( ) => {
37+ notifyWrong ( ) ;
38+ assert . equal ( callCount , 0 , "Expected the handler to not be called, when other events fire" ) ;
39+ } ) ;
40+ } ) ;
41+
42+ describe ( "once" , ( ) => {
43+ it ( "fire once when fired recursively" , ( ) => {
44+ const observable = new Observable ( ) ;
45+ let callCount1 = 0 ;
46+ let callCount2 = 0 ;
47+ const handler2 = function ( ) {
48+ callCount2 ++ ;
49+ }
50+ const handler1 = function ( ) {
51+ callCount1 ++ ;
52+ observable . once ( "test" , handler2 ) ;
53+ observable . notify ( { eventName : "test" , object : observable } ) ;
54+ }
55+ observable . once ( "test" , handler1 ) ;
56+ observable . notify ( { eventName : "test" , object : observable } ) ;
57+ assert . equal ( callCount1 , 1 , "Expected the first handler to unsubscribe before being fired and to notify just once" ) ;
58+ assert . equal ( callCount2 , 1 , "Expected the second handler to be fired once when recursively notified by the first handler" ) ;
59+ } ) ;
60+ } ) ;
61+ } ) ;
0 commit comments