QUnit - 嵌套模块
带有分组测试函数的模块用于定义嵌套模块。QUnit 在深入嵌套模块之前对父模块运行测试,即使它们是先声明的。嵌套模块调用上的 beforeEach 和 afterEach 回调将以 LIFO(后进先出)模式堆叠到父钩子中。您可以使用参数和钩子指定在每个测试之前和之后运行的代码。
钩子还可用于创建将在每个测试的上下文中共享的属性。钩子对象上的任何其他属性都将添加到该上下文中。如果您使用回调参数调用 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 ) { // 这将在父模块的 beforeEach 钩子之后运行 hooks.beforeEach( function( assert ) { assert.ok( true, "nested beforeEach called" ); }); // 这将在父模块的 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>
验证输出
您应该看到以下结果 −