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 js::context::JSContext;
6use js::jsapi::{GCReason, JS_GC};
7
8use crate::dom::RootedPromise;
9use crate::dom::bindings::codegen::Bindings::TestUtilsBinding::TestUtilsMethods;
10use crate::dom::bindings::refcounted::TrustedPromise;
11use crate::dom::globalscope::GlobalScope;
12use crate::dom::promise::Promise;
13
14pub(crate) struct TestUtils;
15
16impl TestUtilsMethods<crate::DomTypeHolder> for TestUtils {
17    /// <https://testutils.spec.whatwg.org/#dom-testutils-gc>
18    #[expect(unsafe_code)]
19    fn Gc(cx: &mut JSContext, global: &GlobalScope) -> RootedPromise {
20        // 1. Let p be a new promise.
21        let promise = Promise::new(cx, global);
22        let trusted = TrustedPromise::from(&promise);
23        // 2. Run the following in parallel:
24        // 2.1 Run implementation-defined steps to perform a garbage collection covering at least the entry Realm.
25        // 2.2 Resolve p.
26        // We need to spin the event-loop in order get the GC to actually run.
27        // We do this by queuing a task that calls the GC and then resolves the promise.
28        let task = task!(testutils_gc: move |cx| {
29            unsafe {
30                JS_GC(cx.raw_cx(), GCReason::DOM_TESTUTILS);
31            }
32            let promise = trusted.root(cx);
33            promise.resolve_native(cx, &());
34        });
35
36        global
37            .task_manager()
38            .dom_manipulation_task_source()
39            .queue(task);
40
41        promise
42    }
43}