QUnit使用笔记-4保持原子性与分组

原子性:

当将许多测试用例放到一起测试的时候,可能会因为相互的副作用而出错;这个时候应该尽可能将他们分别放到test()中测试;

对应测试到Dom,应该尽可能地使用#qunit-fixture,因为它会在一次测试完之后自动清除绑定;

QUnit.test( "Appends a div", function( assert ) {
  var $fixture = $( "#qunit-fixture" );
  $fixture.append( "<div>hello!</div>" );
  equal( $( "div", $fixture ).length, 1, "div added successfully!" );
});
 
QUnit.test( "Appends a span", function( assert ) {
  var $fixture = $( "#qunit-fixture" );
  $fixture.append("<span>hello!</span>" );
  assert.equal( $( "span", $fixture ).length, 1, "span added successfully!" );
});

分组测试:

在将测试分割之后,考虑到逻辑性,可能需要将他们进行分组;使用module( "group A" );  //这里module设置后,会将这个module内设置的方法固定在这个范围内。

QUnit.module( "group a" );
QUnit.test( "a basic test example", function( assert ) {
  assert.ok( true, "this test is fine" );
});
QUnit.test( "a basic test example 2", function( assert ) {
  assert.ok( true, "this test is fine" );
});
 
QUnit.module( "group b" );
QUnit.test( "a basic test example 3", function( assert ) {
  assert.ok( true, "this test is fine" );
});
QUnit.test( "a basic test example 4", function( assert ) {
  assert.ok( true, "this test is fine" );
});

 此外,module还可以设置第二参数,来定义这个module范围内的开始和结束时候的行为:格式

QUnit.module( "module A", {
  setup: function() {
    // prepare something for all following tests
  },
  teardown: function() {
    // clean up after each test
  }
});

范围为到下一个module为止;

原文地址:https://www.cnblogs.com/jinkspeng/p/4026586.html