chromium/third_party/blink/web_tests/fast/media/media-query-list-listener.html

<!DOCTYPE html>
<script src="../../resources/js-test.js"></script>

<div id="sandbox"></div>

<script>
    description("Media query listeners should fire on changes to matches status.");
    var jsTestIsAsync = true;

    var sandbox = document.getElementById("sandbox");
    var iframe = document.createElement("iframe");
    iframe.style.width = "80px";
    sandbox.appendChild(iframe);

    var matchMedia = iframe.contentWindow.matchMedia;
    var mediaList = matchMedia("(max-width: 100px)");
    var expectedValue = "";

    var tests = [];
    var currentTest = 0;
    var callbackCount = 0;
    function runNextTest() {
        tests[currentTest++]();
    }
    function listener(list) {
        callbackCount++;
        window.mediaListArgument = list;
        shouldBe("mediaList.matches", "mediaListArgument.matches");
        shouldBe("mediaList.media", "mediaListArgument.media");
        shouldBe("mediaList.matches", expectedValue);
    }

    tests.push(function() {
        mediaList.addListener(listener);
        // This is the initial value, so should not fire.
        shouldBe("mediaList.matches", "true");
        requestAnimationFrame(() => {
            shouldBe("callbackCount", "0");
            runNextTest();
        });
    });

    tests.push(function() {
        // Should fire.
        iframe.style.width = "200px";
        expectedValue = "false";
        shouldBe("mediaList.matches", "false");
        requestAnimationFrame(() => {
            shouldBe("callbackCount", "1");
            runNextTest();
        });
    });

    tests.push(function() {
        // Should not fire.
        iframe.style.width = "250px";
        expectedValue = "notreached";
        shouldBe("mediaList.matches", "false");
        requestAnimationFrame(() => {
            shouldBe("callbackCount", "1");
            runNextTest();
        });
    });

    tests.push(function() {
        // Should fire.
        iframe.style.width = "80px";
        expectedValue = "true";
        shouldBe("mediaList.matches", "true");
        requestAnimationFrame(() => {
            shouldBe("callbackCount", "2");
            runNextTest();
        });
    });

    tests.push(function() {
        // Should not fire.
        mediaList.removeListener(listener);
        iframe.style.width = "200px";
        expectedValue = "notreached";
        shouldBe("mediaList.matches", "false");
        requestAnimationFrame(() => {
            shouldBe("callbackCount", "2");
            finishJSTest();
        });
    });

    runNextTest();
</script>