1
1
const mysql = require ( 'mysql2' ) ;
2
2
const bcrypt = require ( 'bcryptjs' ) ;
3
3
const ErrsoleMySQL = require ( '../lib/index' ) ; // Adjust the path as needed
4
- const { describe } = require ( '@jest/globals' ) ;
5
-
6
- /* globals expect, jest, beforeEach, it, afterEach */
4
+ const cron = require ( 'node-cron' ) ;
5
+ /* globals expect, jest, beforeEach, it, afterEach, describe, afterAll */
7
6
8
7
jest . mock ( 'mysql2' , ( ) => ( {
9
8
createPool : jest . fn ( )
@@ -19,6 +18,7 @@ describe('ErrsoleMySQL', () => {
19
18
let poolMock ;
20
19
let connectionMock ;
21
20
let originalConsoleError ;
21
+ let cronJob ;
22
22
23
23
beforeEach ( ( ) => {
24
24
connectionMock = {
@@ -42,16 +42,30 @@ describe('ErrsoleMySQL', () => {
42
42
queueLimit : 0
43
43
} ) ;
44
44
45
+ // Mock setInterval and cron.schedule
46
+ jest . useFakeTimers ( ) ;
47
+ jest . spyOn ( global , 'setInterval' ) ;
48
+ cronJob = { stop : jest . fn ( ) } ;
49
+ jest . spyOn ( cron , 'schedule' ) . mockReturnValue ( cronJob ) ;
50
+
45
51
// Suppress console.error
46
52
originalConsoleError = console . error ;
47
53
console . error = jest . fn ( ) ;
48
54
} ) ;
49
55
50
56
afterEach ( ( ) => {
51
57
jest . clearAllMocks ( ) ;
52
-
58
+ jest . useRealTimers ( ) ;
53
59
// Restore console.error
54
60
console . error = originalConsoleError ;
61
+ // Clear the interval if it was set
62
+ if ( errsoleMySQL . flushIntervalId ) {
63
+ clearInterval ( errsoleMySQL . flushIntervalId ) ;
64
+ }
65
+ // Stop the cron job
66
+ if ( cronJob ) {
67
+ cronJob . stop ( ) ;
68
+ }
55
69
} ) ;
56
70
57
71
describe ( '#initialize' , ( ) => {
@@ -70,6 +84,8 @@ describe('ErrsoleMySQL', () => {
70
84
expect ( poolMock . getConnection ) . toHaveBeenCalled ( ) ;
71
85
expect ( poolMock . query ) . toHaveBeenCalledWith ( expect . any ( String ) , expect . any ( Function ) ) ;
72
86
expect ( errsoleMySQL . isConnectionInProgress ) . toBe ( false ) ;
87
+ expect ( setInterval ) . toHaveBeenCalled ( ) ;
88
+ expect ( cron . schedule ) . toHaveBeenCalled ( ) ;
73
89
} ) ;
74
90
} ) ;
75
91
@@ -121,7 +137,6 @@ describe('ErrsoleMySQL', () => {
121
137
expect ( poolMock . query ) . not . toHaveBeenCalledWith ( 'SET SESSION sort_buffer_size = 8388608' , expect . any ( Function ) ) ;
122
138
} ) ;
123
139
} ) ;
124
-
125
140
describe ( '#createTables' , ( ) => {
126
141
it ( 'should create tables if they do not exist' , async ( ) => {
127
142
poolMock . query . mockImplementation ( ( query , cb ) => cb ( null , { affectedRows : 1 } ) ) ;
@@ -900,4 +915,14 @@ describe('ErrsoleMySQL', () => {
900
915
expect ( errsoleMySQL . deleteExpiredLogsRunning ) . toBe ( false ) ;
901
916
} ) ;
902
917
} ) ;
918
+
919
+ afterAll ( ( ) => {
920
+ // Ensure to clear any remaining intervals and cron jobs
921
+ if ( errsoleMySQL . flushIntervalId ) {
922
+ clearInterval ( errsoleMySQL . flushIntervalId ) ;
923
+ }
924
+ if ( cronJob ) {
925
+ cronJob . stop ( ) ;
926
+ }
927
+ } ) ;
903
928
} ) ;
0 commit comments