QUnit - 嵌套模块

具有分组测试功能的模块用于定义嵌套模块.在深入嵌套之前,QUnit会对父模块运行测试,即使它们是先声明的.嵌套模块调用上的 beforeEach afterEach 回调将以LIFO(后进先出)模式堆叠到父挂钩.您可以使用参数和钩子指定在每次测试之前和之后运行的代码.

Hook还可用于创建将在每个测试的上下文中共享的属性.钩子对象上的任何其他属性都将添加到该上下文中.如果使用回调参数调用QUnit.module,则hooks参数是可选的.

调用模块的回调,将上下文作为测试环境,将环境的属性复制到模块的测试中,钩子和嵌套模块.

<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.module( "parent module", function( hooks ) {
            hooks.beforeEach( function( assert ) {
               assert.ok( true, "beforeEach called" );
            });

            hooks.afterEach( function( assert ) {
               assert.ok( true, "afterEach called" );
            });

            QUnit.test( "hook test 1", function( assert ) {
               assert.expect( 2 );
            });

            QUnit.module( "nested hook module", function( hooks ) {
               // This will run after the parent module's beforeEach hook
               hooks.beforeEach( function( assert ) {
                  assert.ok( true, "nested beforeEach called" );
               });

               // This will run before the parent module's afterEach
               hooks.afterEach( function( assert ) {
                  assert.ok( true, "nested afterEach called" );
               });

               QUnit.test( "hook test 2", function( assert ) {
                  assert.expect( 4 );
               });
            });
         });
      </script>

      <div id = "console" ></div>
   </body>
</html>