<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../../resources/js-test-pre.js"></script>
</head>
<body>
<script>

description("Test that promises and mutation observers are both delivered from the same microtask queue.");
var jsTestIsAsync = true;

var actualResult = [];
var expectedResult = [];
var currentTest = 0;

new MutationObserver(function() { 
    actualResult.push('mutate');
    checkIfDone();
}).observe(document.body, { attributes: true });
function mutate()
{
    document.body.setAttribute('data-random', Math.random());
}
function promise()
{
    Promise.resolve().then(function() { 
        actualResult.push('promise');
        checkIfDone();
    });
}
function timeout()
{
    setTimeout(function() {
        actualResult.push('timeout');
        checkIfDone();
    }, 0);
}

function checkIfDone()
{
    if (actualResult.length != expectedResult.length)
        return;

    debug("Expected result: " + expectedResult);
    debug("Actual result: " + actualResult);
    shouldBe("actualResult", "expectedResult");
    debug("");

    ++currentTest
    runNextTest();
}

var tests = [
    [[timeout, promise, mutate], ["promise", "mutate", "timeout"]],
    [[timeout, mutate, promise], ["mutate", "promise", "timeout"]]
];

function runNextTest()
{
    if (currentTest >= tests.length) {
        finishJSTest();
        return;
    }

    actualResult = [];
    tasks = tests[currentTest][0];
    expectedResult = tests[currentTest][1];

    for (task of tasks) {
        task();
    }
}

runNextTest()

</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
