use blitz_script::ScriptDocument;
fn value(doc: &mut ScriptDocument, expression: &str) -> serde_json::Value {
doc.eval_json(expression).unwrap_or(serde_json::Value::Null)
}
fn page() -> ScriptDocument {
ScriptDocument::from_html(
"<html><body><div id='host'></div></body></html>",
blitz_dom::DocumentConfig::default(),
)
}
#[test]
fn a_fragment_can_be_created() {
let mut doc = page();
doc.execute_scripts();
assert_eq!(
value(&mut doc, "typeof document.createDocumentFragment"),
serde_json::json!("function")
);
}
#[test]
fn a_fragment_reports_itself_as_one() {
let mut doc = page();
doc.execute_scripts();
doc.eval("globalThis.f = document.createDocumentFragment();");
assert_eq!(value(&mut doc, "f.nodeType"), serde_json::json!(11));
assert_eq!(
value(&mut doc, "f.nodeName"),
serde_json::json!("#document-fragment")
);
}
#[test]
fn appending_to_a_fragment_returns_the_child() {
let mut doc = page();
doc.execute_scripts();
doc.eval(
"globalThis.kept = document.createDocumentFragment()
.appendChild(document.createElement('div'));",
);
assert_eq!(value(&mut doc, "kept.nodeName"), serde_json::json!("DIV"));
}
#[test]
fn inserting_a_fragment_inserts_its_children() {
let mut doc = page();
doc.execute_scripts();
doc.eval(
"var f = document.createDocumentFragment();
f.appendChild(document.createElement('span'));
f.appendChild(document.createElement('em'));
globalThis.before = f.childNodes.length;
document.getElementById('host').appendChild(f);",
);
let host_children = value(
&mut doc,
"document.getElementById('host').childNodes.length",
);
let names = value(
&mut doc,
"Array.prototype.map.call(
document.getElementById('host').childNodes, function (n) { return n.nodeName; }
).join(',')",
);
assert_eq!(
host_children,
serde_json::json!(2),
"both children should have moved into the host"
);
assert_eq!(names, serde_json::json!("SPAN,EM"));
assert_eq!(
value(&mut doc, "f.childNodes.length"),
serde_json::json!(0),
"the fragment should be empty after insertion"
);
}