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