<!DOCTYPE html>
<script src="../../../resources/js-test-pre.js"></script>
<script>
description('Inserting DocumentFragments should remove all children of the fragment before inserting the children.');

window.jsTestIsAsync = true;

function createObservedFragment() {
    var fragment = document.createDocumentFragment();
    fragment.appendChild(document.createElement('b'));
    fragment.appendChild(document.createElement('i'));
    observer.observe(fragment, {childList: true});
    return fragment;
}

function createObservedDiv() {
    return div;
}

function callback(mutations) {
    window.mutations = mutations;
}
var observer = new MutationObserver(callback);

function testAppendChild() {
    debug('Testing appendChild');
    var div = document.createElement('div');
    observer.observe(div, {childList: true});
    div.appendChild(createObservedFragment());
    setTimeout(function() {
        shouldBe('mutations.length', '2');
        shouldBe('mutations[0].addedNodes.length', '0');
        shouldBe('mutations[0].removedNodes.length', '2');
        shouldBe('mutations[1].addedNodes.length', '2');
        shouldBe('mutations[1].removedNodes.length', '0');
        debug('');
        testInsertBefore();
    }, 0);
}

function testInsertBefore() {
    debug('Testing insertBefore');
    var div = document.createElement('div');
    div.appendChild(document.createElement('span'));
    observer.observe(div, {childList: true});
    div.insertBefore(createObservedFragment(), div.firstChild);
    setTimeout(function() {
        shouldBe('mutations.length', '2');
        shouldBe('mutations[0].addedNodes.length', '0');
        shouldBe('mutations[0].removedNodes.length', '2');
        shouldBe('mutations[1].addedNodes.length', '2');
        shouldBe('mutations[1].removedNodes.length', '0');
        debug('');
        testReplaceChild();
    }, 0);
}

function testReplaceChild() {
    debug('Testing replaceChild');
    var div = document.createElement('div');
    div.appendChild(document.createElement('span'));
    observer.observe(div, {childList: true});
    div.replaceChild(createObservedFragment(), div.firstChild);
    setTimeout(function() {
        shouldBe('mutations.length', '2');
        shouldBe('mutations[0].addedNodes.length', '0');
        shouldBe('mutations[0].removedNodes.length', '2');
        shouldBe('mutations[1].addedNodes.length', '2');
        shouldBe('mutations[1].removedNodes.length', '1');
        debug('');
        finishJSTest();
    }, 0);
}

testAppendChild();
</script>
<script src="../../../resources/js-test-post.js"></script>
