@@ -13,12 +13,20 @@ declare global {
1313
1414let windowObj : Window & typeof globalThis ;
1515
16+ const logSpy = jest . spyOn ( console , 'log' ) ;
17+
1618beforeAll ( ( ) => {
1719 windowObj = window ;
20+
21+ logSpy . mockImplementation ( ) ;
1822} ) ;
1923
2024afterAll ( ( ) => {
21- window = windowObj ;
25+ Object . defineProperty ( global , 'window' , {
26+ value : windowObj ,
27+ } ) ;
28+
29+ logSpy . mockRestore ( ) ;
2230} ) ;
2331
2432describe ( 'getZaraz()' , ( ) => {
@@ -36,11 +44,57 @@ describe('getZaraz()', () => {
3644 } ) ;
3745 } ) ;
3846
39- it ( 'should throw when zaraz does not exist on the window ' , ( ) => {
47+ it ( 'should queue events when zaraz is not defined ' , ( ) => {
4048 window . zaraz = undefined ;
4149
50+ // getZaraz() returns a queue.
51+ getZaraz ( ) . track ( 'page_view' , {
52+ page_location : 'https://example.com' ,
53+ page_path : '/' ,
54+ page_title : 'Home' ,
55+ } ) ;
56+
57+ expect ( logSpy ) . toHaveBeenCalledWith (
58+ `Zaraz Web API is not initialized. Queueing events...` ,
59+ ) ;
60+
61+ window . zaraz = {
62+ track : trackMock ,
63+ set : setMock ,
64+ ecommerce : ecommerceMock ,
65+ } ;
66+
67+ // Triggers the flush.
68+ getZaraz ( ) . track ( 'button clicked' , { userId : 'ABC-123' , value : 200 } ) ;
69+
70+ expect ( logSpy ) . toHaveBeenCalledWith (
71+ `Zaraz Web API is initialized. Flushing queue...` ,
72+ ) ;
73+
74+ // Calls the queued events.
75+ expect ( trackMock ) . toHaveBeenCalledWith ( 'page_view' , {
76+ page_location : 'https://example.com' ,
77+ page_path : '/' ,
78+ page_title : 'Home' ,
79+ } ) ;
80+
81+ // Calls the actual event.
82+ expect ( trackMock ) . toHaveBeenCalledWith ( 'button clicked' , {
83+ userId : 'ABC-123' ,
84+ value : 200 ,
85+ } ) ;
86+
87+ expect ( logSpy ) . toHaveBeenCalledWith ( `Zaraz Web API queue flushed.` ) ;
88+ } ) ;
89+
90+ it ( 'should throw when window is not defined' , ( ) => {
91+ // Set window to undefined.
92+ Object . defineProperty ( global , 'window' , {
93+ value : undefined ,
94+ } ) ;
95+
4296 expect ( ( ) => getZaraz ( ) ) . toThrow (
43- `Cannot use Zaraz Web API, because window.zaraz is not defined.` ,
97+ `Cannot use Zaraz Web API, because window is not defined.` ,
4498 ) ;
4599 } ) ;
46100} ) ;
0 commit comments