Skip to main content

script/dom/testing/
testutils.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::context::JSContext;
7use js::jsapi::{GCReason, JS_GC};
8use script_bindings::reflector::Reflector;
9
10use crate::dom::RootedPromise;
11use crate::dom::bindings::codegen::Bindings::TestUtilsBinding::TestUtilsMethods;
12use crate::dom::globalscope::GlobalScope;
13use crate::dom::promise::Promise;
14use crate::test::TrustedPromise;
15
16#[dom_struct]
17pub(crate) struct TestUtils {
18    reflector_: Reflector,
19}
20
21impl TestUtilsMethods<crate::DomTypeHolder> for TestUtils {
22    /// <https://testutils.spec.whatwg.org/#dom-testutils-gc>
23    #[expect(unsafe_code)]
24    fn Gc(cx: &mut JSContext, global: &GlobalScope) -> RootedPromise {
25        // 1. Let p be a new promise.
26        let promise = Promise::new_rooted(cx, global);
27        let trusted = TrustedPromise::from(&promise);
28        // 2. Run the following in parallel:
29        // 2.1 Run implementation-defined steps to perform a garbage collection covering at least the entry Realm.
30        // 2.2 Resolve p.
31        // We need to spin the event-loop in order get the GC to actually run.
32        // We do this by queuing a task that calls the GC and then resolves the promise.
33        let task = task!(testutils_gc: move |cx| {
34            unsafe {
35                JS_GC(cx.raw_cx(), GCReason::DOM_TESTUTILS);
36            }
37            let promise = trusted.root(cx);
38            promise.resolve_native(cx, &());
39        });
40
41        global
42            .task_manager()
43            .dom_manipulation_task_source()
44            .queue(task);
45
46        promise
47    }
48}