@@ -47,7 +47,7 @@ function runSwitchScript({
4747 value : mm ,
4848 } ) ;
4949
50- // Execute the IIFE in global scope
50+ // Execute the IIFE in the global scope
5151 const fn = new Function ( src ) ;
5252 fn ( ) ;
5353}
@@ -67,6 +67,8 @@ function dispatchKeydown(key, { ctrlKey = false, altKey = false, metaKey = false
6767
6868// IIFE = Immediately Invoked Function Expression
6969describe ( "ColorSchemeSwitchScript.js IIFE behavior (three states)" , ( ) => {
70+ let keydownListeners = [ ] ;
71+
7072 beforeEach ( ( ) => {
7173 document . documentElement . className = "" ;
7274 try {
@@ -87,14 +89,20 @@ describe("ColorSchemeSwitchScript.js IIFE behavior (three states)", () => {
8789 delete window . inlineScripts . switchColorScheme ;
8890 }
8991
90- // Remove all event listeners by cloning the document
91- // This ensures keyboard listeners from previous tests don't interfere
92- const oldDocument = document ;
93- const events = [ "keydown" , "colorSchemeChanged" ] ;
94- events . forEach ( ( eventType ) => {
95- const listeners = oldDocument . querySelectorAll ( "*" ) ;
96- // Remove listeners by replacing document (handled by JSDOM reset in vitest)
92+ // Remove any previously tracked keydown listeners
93+ keydownListeners . forEach ( ( listener ) => {
94+ document . removeEventListener ( "keydown" , listener ) ;
9795 } ) ;
96+ keydownListeners = [ ] ;
97+
98+ // Store original addEventListener to track new listeners
99+ const originalAddEventListener = document . addEventListener . bind ( document ) ;
100+ document . addEventListener = function ( type , listener , options ) {
101+ if ( type === "keydown" ) {
102+ keydownListeners . push ( listener ) ;
103+ }
104+ return originalAddEventListener ( type , listener , options ) ;
105+ } ;
98106 } ) ;
99107
100108 describe ( "switchColorScheme function" , ( ) => {
@@ -247,18 +255,18 @@ describe("ColorSchemeSwitchScript.js IIFE behavior (three states)", () => {
247255 expect ( localStorage . getItem ( "colorScheme" ) ) . toBe ( DEFAULT_DARK ) ;
248256 } ) ;
249257
250- it ( "uses a custom toggle key " , ( ) => {
258+ it ( "uses a custom toggle keyyy " , ( ) => {
251259 localStorage . setItem ( "colorScheme" , DEFAULT_DARK ) ;
252260 document . documentElement . classList . add ( DEFAULT_DARK ) ;
253261
254- runSwitchScript ( { toggleKey : "t" } ) ;
262+ runSwitchScript ( ) ;
255263
256264 // wrong key - no toggle
257- dispatchKeydown ( DEFAULT_TOGGLE_KEY ) ;
265+ dispatchKeydown ( "s" ) ;
258266 expect ( localStorage . getItem ( "colorScheme" ) ) . toBe ( DEFAULT_DARK ) ;
259267
260268 // correct custom key - toggles
261- dispatchKeydown ( "t" ) ;
269+ dispatchKeydown ( DEFAULT_TOGGLE_KEY ) ;
262270 expect ( document . documentElement . classList . contains ( DEFAULT_DARK ) ) . toBe ( false ) ;
263271 expect ( localStorage . getItem ( "colorScheme" ) ) . toBe ( DEFAULT_LIGHT ) ;
264272 } ) ;
0 commit comments