QUnit - 巢狀模組



用於定義巢狀模組的模組包含分組的測試函式。即使先聲明瞭巢狀模組,QUnit 也會先在父模組上執行測試,再深入執行巢狀模組。巢狀模組回撥中的 beforeEachafterEach 回撥將使用 LIFO(後進先出)模式堆疊到父掛鉤。你可以使用引數和掛鉤指定每個測試前後要執行的程式碼。

掛鉤也可用於建立將在每個測試上下文中共享的屬性。掛鉤物件上的任何其他屬性都將新增到該上下文中。如果你使用回撥引數呼叫 QUnit.module,則掛鉤引數是可選的。

模組的回撥以與測試環境相同的上下文進行呼叫,環境屬性將複製到模組的測試、掛鉤和巢狀模組中。

<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>

驗證輸出

你應該看到以下結果−

廣告
© . All rights reserved.