reinhardt-test 0.1.2

Testing utilities and helpers for Reinhardt framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
#![cfg(wasm)]

//! Async utilities for WASM testing.
//!
//! This module provides async waiting utilities for handling asynchronous operations
//! in WASM tests, including condition-based waiting, element visibility waiting,
//! and microtask/effect flushing.
//!
//! # Example
//!
//! ```no_run
//! use reinhardt_test::wasm::wait::{wait_for, sleep, WaitOptions};
//!
//! // Wait for a condition
//! wait_for(|| document.get_element_by_id("result").is_some())
//!     .await
//!     .expect("Element should appear");
//!
//! // Wait with custom timeout
//! wait_for(|| some_condition())
//!     .with_timeout(Duration::from_secs(5))
//!     .await?;
//!
//! // Simple sleep
//! sleep(Duration::from_millis(100)).await;
//! ```

#![cfg(wasm)]

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

use gloo_timers::future::TimeoutFuture;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Document, Element, Window};

/// Default timeout for wait operations (5 seconds).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);

/// Default interval for polling conditions (50ms).
pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(50);

/// Error type for wait operations.
#[derive(Debug, Clone)]
pub enum WaitError {
	/// The operation timed out.
	Timeout {
		/// The timeout duration that was exceeded.
		timeout: Duration,
		/// Optional description of what was being waited for.
		description: Option<String>,
	},
	/// A JavaScript error occurred.
	JsError(String),
	/// The element was not found.
	ElementNotFound(String),
}

impl std::fmt::Display for WaitError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			WaitError::Timeout {
				timeout,
				description,
			} => {
				if let Some(desc) = description {
					write!(f, "Timed out after {:?} waiting for: {}", timeout, desc)
				} else {
					write!(f, "Timed out after {:?}", timeout)
				}
			}
			WaitError::JsError(msg) => write!(f, "JavaScript error: {}", msg),
			WaitError::ElementNotFound(selector) => {
				write!(f, "Element not found: {}", selector)
			}
		}
	}
}

impl std::error::Error for WaitError {}

/// Result type for wait operations.
pub type WaitResult<T> = Result<T, WaitError>;

/// Options for configuring wait behavior.
#[derive(Debug, Clone)]
pub struct WaitOptions {
	/// Maximum time to wait before timing out.
	pub timeout: Duration,
	/// Interval between condition checks.
	pub interval: Duration,
	/// Optional description for error messages.
	pub description: Option<String>,
}

impl Default for WaitOptions {
	fn default() -> Self {
		Self {
			timeout: DEFAULT_TIMEOUT,
			interval: DEFAULT_INTERVAL,
			description: None,
		}
	}
}

impl WaitOptions {
	/// Create new wait options with default values.
	pub fn new() -> Self {
		Self::default()
	}

	/// Set the timeout duration.
	pub fn with_timeout(mut self, timeout: Duration) -> Self {
		self.timeout = timeout;
		self
	}

	/// Set the polling interval.
	pub fn with_interval(mut self, interval: Duration) -> Self {
		self.interval = interval;
		self
	}

	/// Set a description for error messages.
	pub fn with_description(mut self, description: impl Into<String>) -> Self {
		self.description = Some(description.into());
		self
	}
}

/// Builder for wait_for operations with fluent API.
pub struct WaitForBuilder<F>
where
	F: FnMut() -> bool,
{
	condition: F,
	options: WaitOptions,
}

impl<F> WaitForBuilder<F>
where
	F: FnMut() -> bool,
{
	/// Create a new wait builder with the given condition.
	pub fn new(condition: F) -> Self {
		Self {
			condition,
			options: WaitOptions::default(),
		}
	}

	/// Set the timeout duration.
	pub fn with_timeout(mut self, timeout: Duration) -> Self {
		self.options.timeout = timeout;
		self
	}

	/// Set the polling interval.
	pub fn with_interval(mut self, interval: Duration) -> Self {
		self.options.interval = interval;
		self
	}

	/// Set a description for error messages.
	pub fn with_description(mut self, description: impl Into<String>) -> Self {
		self.options.description = Some(description.into());
		self
	}

	/// Execute the wait operation.
	pub async fn await_condition(mut self) -> WaitResult<()> {
		let start = js_sys::Date::now();
		let timeout_ms = self.options.timeout.as_millis() as f64;
		let interval_ms = self.options.interval.as_millis() as u32;

		loop {
			// Check the condition
			if (self.condition)() {
				return Ok(());
			}

			// Check timeout
			let elapsed = js_sys::Date::now() - start;
			if elapsed >= timeout_ms {
				return Err(WaitError::Timeout {
					timeout: self.options.timeout,
					description: self.options.description.clone(),
				});
			}

			// Wait for interval
			TimeoutFuture::new(interval_ms).await;
		}
	}
}

impl<F> std::future::IntoFuture for WaitForBuilder<F>
where
	F: FnMut() -> bool + 'static,
{
	type Output = WaitResult<()>;
	type IntoFuture = Pin<Box<dyn Future<Output = Self::Output>>>;

	fn into_future(self) -> Self::IntoFuture {
		Box::pin(self.await_condition())
	}
}

/// Wait for a condition to become true.
///
/// Returns a builder that can be configured with timeout and interval options.
///
/// # Example
///
/// ```no_run
/// use reinhardt_test::wasm::wait::wait_for;
/// use std::time::Duration;
///
/// // Simple usage
/// wait_for(|| some_condition()).await?;
///
/// // With custom timeout
/// wait_for(|| some_condition())
///     .with_timeout(Duration::from_secs(10))
///     .await?;
/// ```
pub fn wait_for<F>(condition: F) -> WaitForBuilder<F>
where
	F: FnMut() -> bool,
{
	WaitForBuilder::new(condition)
}

/// Wait for an element to become visible in the DOM.
///
/// # Arguments
///
/// * `selector` - CSS selector for the element
/// * `options` - Optional wait configuration
///
/// # Example
///
/// ```no_run
/// use reinhardt_test::wasm::wait::wait_for_element_visible;
///
/// let element = wait_for_element_visible("#loading-spinner", None).await?;
/// ```
pub async fn wait_for_element_visible(
	selector: &str,
	options: Option<WaitOptions>,
) -> WaitResult<Element> {
	let opts = options.unwrap_or_else(|| {
		WaitOptions::default().with_description(format!("element '{}' to be visible", selector))
	});

	let selector_owned = selector.to_string();
	let document = get_document()?;

	let start = js_sys::Date::now();
	let timeout_ms = opts.timeout.as_millis() as f64;
	let interval_ms = opts.interval.as_millis() as u32;

	loop {
		if let Some(element) = document.query_selector(&selector_owned).ok().flatten() {
			if is_element_visible(&element) {
				return Ok(element);
			}
		}

		let elapsed = js_sys::Date::now() - start;
		if elapsed >= timeout_ms {
			return Err(WaitError::Timeout {
				timeout: opts.timeout,
				description: opts.description.clone(),
			});
		}

		TimeoutFuture::new(interval_ms).await;
	}
}

/// Wait for an element to become hidden or removed from the DOM.
///
/// # Arguments
///
/// * `selector` - CSS selector for the element
/// * `options` - Optional wait configuration
///
/// # Example
///
/// ```no_run
/// use reinhardt_test::wasm::wait::wait_for_element_hidden;
///
/// wait_for_element_hidden("#loading-spinner", None).await?;
/// ```
pub async fn wait_for_element_hidden(
	selector: &str,
	options: Option<WaitOptions>,
) -> WaitResult<()> {
	let opts = options.unwrap_or_else(|| {
		WaitOptions::default().with_description(format!("element '{}' to be hidden", selector))
	});

	let selector_owned = selector.to_string();
	let document = get_document()?;

	let start = js_sys::Date::now();
	let timeout_ms = opts.timeout.as_millis() as f64;
	let interval_ms = opts.interval.as_millis() as u32;

	loop {
		let element = document.query_selector(&selector_owned).ok().flatten();

		// Element is hidden if it doesn't exist or is not visible
		if element.is_none() || !is_element_visible(element.as_ref().unwrap()) {
			return Ok(());
		}

		let elapsed = js_sys::Date::now() - start;
		if elapsed >= timeout_ms {
			return Err(WaitError::Timeout {
				timeout: opts.timeout,
				description: opts.description.clone(),
			});
		}

		TimeoutFuture::new(interval_ms).await;
	}
}

/// Wait for an element matching the selector to appear in the DOM.
///
/// This doesn't check visibility, only presence in the DOM.
///
/// # Arguments
///
/// * `selector` - CSS selector for the element
/// * `options` - Optional wait configuration
pub async fn wait_for_element(selector: &str, options: Option<WaitOptions>) -> WaitResult<Element> {
	let opts = options.unwrap_or_else(|| {
		WaitOptions::default().with_description(format!("element '{}' to appear in DOM", selector))
	});

	let selector_owned = selector.to_string();
	let document = get_document()?;

	let start = js_sys::Date::now();
	let timeout_ms = opts.timeout.as_millis() as f64;
	let interval_ms = opts.interval.as_millis() as u32;

	loop {
		if let Some(element) = document.query_selector(&selector_owned).ok().flatten() {
			return Ok(element);
		}

		let elapsed = js_sys::Date::now() - start;
		if elapsed >= timeout_ms {
			return Err(WaitError::Timeout {
				timeout: opts.timeout,
				description: opts.description.clone(),
			});
		}

		TimeoutFuture::new(interval_ms).await;
	}
}

/// Wait for an element to be removed from the DOM.
///
/// # Arguments
///
/// * `selector` - CSS selector for the element
/// * `options` - Optional wait configuration
pub async fn wait_for_element_removed(
	selector: &str,
	options: Option<WaitOptions>,
) -> WaitResult<()> {
	let opts = options.unwrap_or_else(|| {
		WaitOptions::default()
			.with_description(format!("element '{}' to be removed from DOM", selector))
	});

	let selector_owned = selector.to_string();
	let document = get_document()?;

	let start = js_sys::Date::now();
	let timeout_ms = opts.timeout.as_millis() as f64;
	let interval_ms = opts.interval.as_millis() as u32;

	loop {
		if document
			.query_selector(&selector_owned)
			.ok()
			.flatten()
			.is_none()
		{
			return Ok(());
		}

		let elapsed = js_sys::Date::now() - start;
		if elapsed >= timeout_ms {
			return Err(WaitError::Timeout {
				timeout: opts.timeout,
				description: opts.description.clone(),
			});
		}

		TimeoutFuture::new(interval_ms).await;
	}
}

/// Sleep for the specified duration.
///
/// # Example
///
/// ```no_run
/// use reinhardt_test::wasm::wait::sleep;
/// use std::time::Duration;
///
/// sleep(Duration::from_millis(100)).await;
/// ```
pub async fn sleep(duration: Duration) {
	TimeoutFuture::new(duration.as_millis() as u32).await;
}

/// Flush all pending microtasks.
///
/// This uses `queueMicrotask` to schedule a callback that resolves when
/// the microtask queue is empty.
///
/// # Example
///
/// ```no_run
/// use reinhardt_test::wasm::wait::flush_microtasks;
///
/// // After triggering some async operation
/// flush_microtasks().await;
/// ```
pub async fn flush_microtasks() {
	// Use Promise.resolve() to queue a microtask
	let promise = js_sys::Promise::resolve(&JsValue::UNDEFINED);
	let _ = JsFuture::from(promise).await;
}

/// Flush pending effects and reactive updates.
///
/// This is useful when testing reactive components that use Signal/Effect/Memo.
/// It waits for a short duration to allow effects to propagate.
///
/// # Example
///
/// ```no_run
/// use reinhardt_test::wasm::wait::flush_effects;
///
/// signal.set(new_value);
/// flush_effects().await;
/// // Now check the DOM for updates
/// ```
pub async fn flush_effects() {
	// First flush microtasks
	flush_microtasks().await;

	// Then wait one animation frame to allow effects to run
	request_animation_frame().await;

	// Flush any microtasks queued by effects
	flush_microtasks().await;
}

/// Wait for the next animation frame.
///
/// This is useful for waiting for visual updates to be applied.
pub async fn request_animation_frame() {
	let window = get_window().expect("window should be available in WASM environment");

	let promise = js_sys::Promise::new(&mut |resolve, _reject| {
		let closure = Closure::once_into_js(move || {
			resolve
				.call0(&JsValue::UNDEFINED)
				.expect("Promise resolve callback should not fail");
		});
		window
			.request_animation_frame(closure.unchecked_ref())
			.expect("requestAnimationFrame should be available in browser environment");
	});

	let _ = JsFuture::from(promise).await;
}

/// Wait for multiple animation frames.
///
/// # Arguments
///
/// * `count` - Number of frames to wait
pub async fn wait_frames(count: u32) {
	for _ in 0..count {
		request_animation_frame().await;
	}
}

/// Wait for the DOM to stabilize (no mutations for the specified duration).
///
/// This is useful for waiting for complex animations or transitions to complete.
///
/// # Arguments
///
/// * `stability_duration` - Duration with no DOM mutations to consider stable
/// * `timeout` - Maximum time to wait
pub async fn wait_for_dom_stable(
	stability_duration: Duration,
	timeout: Duration,
) -> WaitResult<()> {
	let start = js_sys::Date::now();
	let timeout_ms = timeout.as_millis() as f64;
	let stability_ms = stability_duration.as_millis() as u32;

	// Use a simple polling approach - check if content hash changes
	let document = get_document()?;
	let mut last_content = get_body_content(&document);
	let mut stable_since = js_sys::Date::now();

	loop {
		let current_content = get_body_content(&document);

		if current_content != last_content {
			last_content = current_content;
			stable_since = js_sys::Date::now();
		} else {
			let stable_duration = js_sys::Date::now() - stable_since;
			if stable_duration >= stability_ms as f64 {
				return Ok(());
			}
		}

		let elapsed = js_sys::Date::now() - start;
		if elapsed >= timeout_ms {
			return Err(WaitError::Timeout {
				timeout,
				description: Some("DOM to stabilize".to_string()),
			});
		}

		TimeoutFuture::new(16).await; // ~60fps
	}
}

// Helper functions

fn get_window() -> WaitResult<Window> {
	web_sys::window().ok_or_else(|| WaitError::JsError("Window not available".to_string()))
}

fn get_document() -> WaitResult<Document> {
	get_window()?
		.document()
		.ok_or_else(|| WaitError::JsError("Document not available".to_string()))
}

fn is_element_visible(element: &Element) -> bool {
	// Check if element has display: none or visibility: hidden
	if let Some(html_element) = element.dyn_ref::<web_sys::HtmlElement>() {
		// Check offsetParent - if null, element is hidden
		if html_element.offset_parent().is_none() {
			// Exception: fixed/sticky positioned elements may have no offsetParent
			if let Ok(style) = get_window()
				.ok()
				.and_then(|w| w.get_computed_style(element).ok())
				.flatten()
				.ok_or(())
			{
				let position = style.get_property_value("position").unwrap_or_default();
				if position != "fixed" && position != "sticky" {
					return false;
				}
			} else {
				return false;
			}
		}

		// Check computed visibility
		if let Some(style) = get_window()
			.ok()
			.and_then(|w| w.get_computed_style(element).ok())
			.flatten()
		{
			let visibility: String = style.get_property_value("visibility").unwrap_or_default();
			let display: String = style.get_property_value("display").unwrap_or_default();

			if visibility == "hidden" || display == "none" {
				return false;
			}
		}

		return true;
	}

	// For non-HTML elements (SVG, etc.), assume visible if in DOM
	true
}

fn get_body_content(document: &Document) -> String {
	document.body().map(|b| b.inner_html()).unwrap_or_default()
}

/// Extension trait for adding wait functionality to elements.
pub trait ElementWaitExt {
	/// Wait for this element to become visible.
	fn wait_until_visible(&self, options: Option<WaitOptions>) -> WaitForVisibleFuture;

	/// Wait for this element to become hidden.
	fn wait_until_hidden(&self, options: Option<WaitOptions>) -> WaitForHiddenFuture;
}

impl ElementWaitExt for Element {
	fn wait_until_visible(&self, options: Option<WaitOptions>) -> WaitForVisibleFuture {
		WaitForVisibleFuture {
			element: self.clone(),
			options: options.unwrap_or_default(),
			started: false,
			start_time: 0.0,
			pending_closure: None,
		}
	}

	fn wait_until_hidden(&self, options: Option<WaitOptions>) -> WaitForHiddenFuture {
		WaitForHiddenFuture {
			element: self.clone(),
			options: options.unwrap_or_default(),
			started: false,
			start_time: 0.0,
			pending_closure: None,
		}
	}
}

/// Future for waiting until an element becomes visible.
// Fixes #877
pub struct WaitForVisibleFuture {
	element: Element,
	options: WaitOptions,
	started: bool,
	start_time: f64,
	/// Stored closure to prevent memory leak from `Closure::forget()`.
	/// The closure is kept alive until the timeout fires or the future completes.
	pending_closure: Option<Closure<dyn FnMut()>>,
}

impl Future for WaitForVisibleFuture {
	type Output = WaitResult<()>;

	fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		if !self.started {
			self.started = true;
			self.start_time = js_sys::Date::now();
		}

		if is_element_visible(&self.element) {
			return Poll::Ready(Ok(()));
		}

		let elapsed = js_sys::Date::now() - self.start_time;
		if elapsed >= self.options.timeout.as_millis() as f64 {
			return Poll::Ready(Err(WaitError::Timeout {
				timeout: self.options.timeout,
				description: self.options.description.clone(),
			}));
		}

		// Schedule a wake-up
		let waker = cx.waker().clone();
		let interval_ms = self.options.interval.as_millis() as i32;

		let closure = Closure::once(move || {
			waker.wake();
		});

		if let Ok(window) = get_window() {
			let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
				closure.as_ref().unchecked_ref(),
				interval_ms,
			);
		}

		// Store closure to keep it alive until the timeout fires,
		// instead of leaking it with `forget()`.
		self.pending_closure = Some(closure);

		Poll::Pending
	}
}

/// Future for waiting until an element becomes hidden.
// Fixes #877
pub struct WaitForHiddenFuture {
	element: Element,
	options: WaitOptions,
	started: bool,
	start_time: f64,
	/// Stored closure to prevent memory leak from `Closure::forget()`.
	/// The closure is kept alive until the timeout fires or the future completes.
	pending_closure: Option<Closure<dyn FnMut()>>,
}

impl Future for WaitForHiddenFuture {
	type Output = WaitResult<()>;

	fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		if !self.started {
			self.started = true;
			self.start_time = js_sys::Date::now();
		}

		if !is_element_visible(&self.element) {
			return Poll::Ready(Ok(()));
		}

		let elapsed = js_sys::Date::now() - self.start_time;
		if elapsed >= self.options.timeout.as_millis() as f64 {
			return Poll::Ready(Err(WaitError::Timeout {
				timeout: self.options.timeout,
				description: self.options.description.clone(),
			}));
		}

		// Schedule a wake-up
		let waker = cx.waker().clone();
		let interval_ms = self.options.interval.as_millis() as i32;

		let closure = Closure::once(move || {
			waker.wake();
		});

		if let Ok(window) = get_window() {
			let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
				closure.as_ref().unchecked_ref(),
				interval_ms,
			);
		}

		// Store closure to keep it alive until the timeout fires,
		// instead of leaking it with `forget()`.
		self.pending_closure = Some(closure);

		Poll::Pending
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	// Note: WASM tests should use wasm_bindgen_test
	// These tests are for compile-time verification only

	// ==================== WaitOptions tests ====================

	#[rstest]
	fn test_wait_options_default_values() {
		// Arrange & Act
		let opts = WaitOptions::default();

		// Assert
		assert_eq!(opts.timeout, Duration::from_secs(5));
		assert_eq!(opts.interval, Duration::from_millis(50));
		assert_eq!(opts.description, None);
	}

	#[rstest]
	fn test_wait_options_new_equals_default() {
		// Arrange & Act
		let from_new = WaitOptions::new();
		let from_default = WaitOptions::default();

		// Assert
		assert_eq!(from_new.timeout, from_default.timeout);
		assert_eq!(from_new.interval, from_default.interval);
		assert_eq!(from_new.description, from_default.description);
	}

	#[rstest]
	fn test_wait_options_with_timeout() {
		// Arrange & Act
		let opts = WaitOptions::new().with_timeout(Duration::from_secs(30));

		// Assert
		assert_eq!(opts.timeout, Duration::from_secs(30));
		// Other fields remain default
		assert_eq!(opts.interval, Duration::from_millis(50));
		assert_eq!(opts.description, None);
	}

	#[rstest]
	fn test_wait_options_with_interval() {
		// Arrange & Act
		let opts = WaitOptions::new().with_interval(Duration::from_millis(200));

		// Assert
		assert_eq!(opts.interval, Duration::from_millis(200));
		// Other fields remain default
		assert_eq!(opts.timeout, Duration::from_secs(5));
		assert_eq!(opts.description, None);
	}

	#[rstest]
	fn test_wait_options_with_description() {
		// Arrange & Act
		let opts = WaitOptions::new().with_description("loading spinner");

		// Assert
		assert_eq!(opts.description, Some("loading spinner".to_string()));
		// Other fields remain default
		assert_eq!(opts.timeout, Duration::from_secs(5));
		assert_eq!(opts.interval, Duration::from_millis(50));
	}

	#[rstest]
	fn test_wait_options_builder_chaining() {
		// Arrange & Act
		let opts = WaitOptions::new()
			.with_timeout(Duration::from_secs(10))
			.with_interval(Duration::from_millis(100))
			.with_description("test wait");

		// Assert
		assert_eq!(opts.timeout, Duration::from_secs(10));
		assert_eq!(opts.interval, Duration::from_millis(100));
		assert_eq!(opts.description, Some("test wait".to_string()));
	}

	// ==================== WaitError Display tests ====================

	#[rstest]
	fn test_wait_error_timeout_with_description() {
		// Arrange
		let error = WaitError::Timeout {
			timeout: Duration::from_secs(5),
			description: Some("element to appear".to_string()),
		};

		// Act
		let msg = error.to_string();

		// Assert
		assert!(msg.contains("5s"));
		assert!(msg.contains("element to appear"));
		assert!(msg.contains("Timed out"));
	}

	#[rstest]
	fn test_wait_error_timeout_without_description() {
		// Arrange
		let error = WaitError::Timeout {
			timeout: Duration::from_secs(3),
			description: None,
		};

		// Act
		let msg = error.to_string();

		// Assert
		assert!(msg.contains("3s"));
		assert!(msg.contains("Timed out"));
		// Should not contain "waiting for:" when description is None
		assert!(!msg.contains("waiting for:"));
	}

	#[rstest]
	fn test_wait_error_js_error_display() {
		// Arrange
		let error = WaitError::JsError("TypeError: undefined is not a function".to_string());

		// Act
		let msg = error.to_string();

		// Assert
		assert!(msg.contains("JavaScript error"));
		assert!(msg.contains("TypeError: undefined is not a function"));
	}

	#[rstest]
	fn test_wait_error_element_not_found_display() {
		// Arrange
		let error = WaitError::ElementNotFound("#missing-element".to_string());

		// Act
		let msg = error.to_string();

		// Assert
		assert!(msg.contains("Element not found"));
		assert!(msg.contains("#missing-element"));
	}

	#[rstest]
	fn test_wait_error_implements_std_error() {
		// Arrange
		let error = WaitError::JsError("test".to_string());

		// Act
		let std_error: &dyn std::error::Error = &error;

		// Assert: source() returns None for all WaitError variants
		assert!(std_error.source().is_none());
	}

	// ==================== Constants tests ====================

	#[rstest]
	fn test_default_timeout_constant() {
		// Arrange & Act & Assert
		assert_eq!(DEFAULT_TIMEOUT, Duration::from_secs(5));
	}

	#[rstest]
	fn test_default_interval_constant() {
		// Arrange & Act & Assert
		assert_eq!(DEFAULT_INTERVAL, Duration::from_millis(50));
	}
}