QUnit源码阅读(3):asyncTest基本执行流程

本文通过源码分析QUnit的asyncTest执行流程,从编写异步测试开始,逐步讲解QUnit如何处理异步测试的初始化、回调执行、流程控制,以及stop和start在其中的作用,揭示异步测试背后的实现细节。
摘要由CSDN通过智能技术生成
//asyncTest, QUnit中的异步测试,具体参考QUnit官方文档。
//直接上代码
//step 1: write a simple asyncTest as the following.
asyncTest("asynchronous test: one second later!", function() {
    expect(1);

    setTimeout(function() {
        ok(true, "Passed and ready to resume!");
        start();
    }, 1000);
});


//step 2: 调用test函数
QUnit = {

    asyncTest: function( testName, expected, callback ) {
        if (arguments.length === 2) {
            callback = expected;
            expected = null;
        }

        QUnit.test(testName, expected, callback, true);
    },

    //...
    test : function(testName, expected, callback, async) {
        //...

        //初始化test,
        test = new Test({
            name : name,
            testName : testName,
            expected : expected,
            async : async, //☆☆☆ if asyncTest  then set async = true; else set async = undefined;
            callback : callback, //回调函数, very important
            module : config.currentModule,
            moduleTestEnvironment : config.currentModuleTestEnvironment,
            stack : sourceFromStacktrace(2)
        });

        if (!validTest(test)) {
            return;
        }

        test.queue();
    },
    //...
}

//step 3: 调用test.queue函数,在config.queue中存入test.init和queue的内置函数run。
Test.prototype = {
    //...
    queue : function() {
        var bad, test = this;

        synchronize(function() {
            test.init();
        });
        function run() {
            // each of these can by async
            synchronize(function() {
                test.setup();
            });
            synchronize(function() {
                test.run();
            });
            synchronize(function() {
                test.teardown();
            });
            synchronize(function() {
                test.finish();
            });
        }

        // `bad` initialized at top of scope
        // defer when previous test run passed, if storage is available
        bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getIt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值