QUnit官方文檔譯文(不完整版)-2.62

QUnit官方文檔譯文

主要方法

- module

QUnit.module(name [,hooks] [,nested])
使用單個標籤對測試進行分組android

參數 描述
name(string) 用來標誌一組測試
hooks(object) 在執行測試時的回調
nested(function) 嵌套模塊的回調

hooks的屬性:{before, beforeEach, afterEach, after}

參數 描述
before (function) 執行第一個測試以前運行
beforeEach (function) 每一個測試以前運行
afterEach (function) 每一個測試以後運行
after (function) 最後一個測試以後運行

提示:若是module的隊列爲空了以後定義了額外的測試方法,after這個鉤子不會再次運行。es6

嵌套模塊: nested( hooks )

當前模塊下的一組測試和嵌套模塊的回調正則表達式

參數 描述
hooks (object) 定義了before/beforeEach/afterEach/after鉤子的對象

描述

你能夠用模塊名稱來組織、選擇、篩選你要運行的測試。數據庫

全部的測試都是放在module的回調函數裏來進行分組的。在測試結果裏都是模塊名稱打頭的,後面纔是跟着具體的測試名稱。其餘模塊能夠嵌套在這個回調函數中,其中它們的測試名稱將由它們的名稱標記,並以其父模塊爲前綴。數組

若是QUnit.module定義的時候沒有nested回調參數,全部後來定義的測試方法都被分組到這個模塊裏,直到另外一個模塊被定義。promise

有一組測試方法的module能夠定義嵌套的module,在深刻嵌套以前,QUnit會先在父module上跑測試,即便那些嵌套的module在父module最頂部定義了。此外,父模塊上的任何鉤子回調都會將掛鉤包裝在嵌套模塊上。換句話說,before 和 beforeEach回調會造成一個隊列,afterEach 和 after會造成一個棧。異步

你能夠用鉤子指定你在測試以前或測試以後須要作的事情,還能夠建立用來在module內部的測試方法之間共享屬性。鉤子對象上的任何其餘屬性都將添加到該module中。若是你嵌套了子module,hooks參數是可選的。async

The module’s callback is invoked with the test environment as its this context, with the environment’s properties copied to the module’s tests, hooks, and nested modules. Note that changes on tests’ this are not preserved between sibling tests, where this will be reset to the initial value for each test.ide

若是你的回調函數返回了了一個then,可用的Promise,QUnit.module的鉤子能自動幫你進行一部結果的解析。函數

指定運行測試代碼

當你在調試你的代碼時,一般只須要運行一部分的測試代碼。那你能夠在QUnit.module後加上only告訴QUnit你想要運行的module。

若是有多個 QUnit.module.only(),則只運行最早定義的。

QUnit.only()也能夠運行。

指定跳過測試代碼

隨着代碼愈來愈龐大,你會發現有些與功能相關的測試因爲某些緣由暫時中斷。在你找到bug以前,你可使用skip跳過這些損壞的模塊。

若是子組件和測試包含一些todo或僅僅是tests,QUnit也會跳過這些測試代碼。

正在編寫的測試

當這個module還在編寫階段,你能夠用 QUnit.module.todo來標記。

Using this method will mark all underlying tests as todo as if they were defined using QUnit.todo except for tests defined using QUnit.skip() which will be left intact. Those tests will pass as long as one failing assertion is present.

If all assertions pass, then the tests will fail signaling that QUnit.module.todo should be replaced by QUnit.module.

例子

使用QUnit.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" );
    });

使用現代語法

QUnit.module( "group a" );

test( "a basic test example", t => {
  t.ok( true, "this test is fine" );
});
test( "a basic test example 2", t => {
  t.ok( true, "this test is fine" );
});

QUnit.module( "group b" );
test( "a basic test example 3", t => {
  t.ok( true, "this test is fine" );
});
test( "a basic test example 4", t => {
  t.ok( true, "this test is fine" );
});

嵌套用法

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

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

  QUnit.module( "nested module b.1", function() {

    // This test will be prefixed with the following module label:
    // "module b > nested module b.1"
    QUnit.test( "a basic test example 3", function( assert ) {
      assert.ok( true, "this test is fine" );
    });
  });
});

使用現代語法

const { test } = QUnit;
QUnit.module( "module a", () => {
  test( "a basic test example", t => {
    t.ok( true, "this test is fine" );
  });
});

QUnit.module( "module b", () => {
  test( "a basic test example 2", t => {
    t.ok( true, "this test is fine" );
  });

  QUnit.module( "nested module b.1", () => {

    // This test will be prefixed with the following module label:
    // "module b > nested module b.1"
    test( "a basic test example 3", t => {
      t.ok( true, "this test is fine" );
    });
  });
});

before, beforeEach, afterEach, and after 鉤子的用法

QUnit.module( "module A", {
  before: function() {
    // prepare something once for all tests
  },
  beforeEach: function() {
    // prepare something before each test
  },
  afterEach: function() {
    // clean up after each test
  },
  after: function() {
    // clean up once after all tests are done
  }
});

共同上下文環境的鉤子和測試共享變量

QUnit.module( "Machine Maker", {
  beforeEach: function() {
    this.maker = new Maker();
    this.parts = [ "wheels", "motor", "chassis" ];
  }
});

QUnit.test( "makes a robot", function( assert ) {
  this.parts.push( "arduino" );
  assert.equal( this.maker.build( this.parts ), "robot" );
  assert.deepEqual( this.maker.made, [ "robot" ] );
});

QUnit.test( "makes a car", function( assert ) {
  assert.equal( this.maker.build( this.parts ), "car" );
  this.maker.duplicate();
  assert.deepEqual( this.maker.made, [ "car", "car" ] );
});

before/beforeEach鉤子在嵌套模塊中以隊列方式調用,after/afterEach鉤子在嵌套模塊中以棧方式調用

QUnit.module( "grouped tests argument hooks", function( hooks ) {

  // You can invoke the hooks methods more than once.
  hooks.beforeEach( function( assert ) {
    assert.ok( true, "beforeEach called" );
  } );

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

  QUnit.test( "call hooks", function( assert ) {
    assert.expect( 2 );
  } );

  QUnit.module( "stacked hooks", 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( "call hooks", function( assert ) {
      assert.expect( 4 );
    } );
  } );
} );

在鉤子裏處理異步返回的例子,例子使用es6的Promise接口,操做是鏈接、斷開數據庫

QUnit.module( "Database connection", {
  before: function() {
    return new Promise( function( resolve, reject ) {
      DB.connect( function( err ) {
        if ( err ) {
          reject( err );
        } else {
          resolve();
        }
      } );
    } );
  },
  after: function() {
    return new Promise( function( resolve, reject ) {
      DB.disconnect( function( err ) {
        if ( err ) {
          reject( err );
        } else {
          resolve();
        }
      } );
    } );
  }
} );

只跑一部分測試代碼

QUnit.module( "Robot", function() {
  // ...
} );

// Currenly working on implementing features related to androids
QUnit.module.only( "Android", function( hooks ) {
  hooks.beforeEach( function() {
    this.android = new Android();
  } );

  QUnit.test( "Say hello", function( assert ) {
    assert.strictEqual( this.android.hello(), "Hello, my name is AN-2178!" );
  } );

  QUnit.test( "Basic conversation", function( assert ) {
    this.android.loadConversationData( {
      "Hi": "Hello",
      "What's your name?": "My name is AN-2178.",
      "Nice to meet you!": "Nice to meet you too!",
      "...": "..."
    } );

    assert.strictEqual(
      this.android.answer( "What's your name?" ), "My name is AN-2178."
    );
  } );

  // ...
} );

跳過損壞模塊

QUnit.module( "Robot", function() {
  // ...
} );

// Tests related to androids are failling due to unkown cause.
// Skipping them for now.
QUnit.module.skip( "Android", function( hooks ) {
  hooks.beforeEach( function() {
    this.android = new Android();
  } );

  QUnit.test( "Say hello", function( assert ) {
    assert.strictEqual( this.android.hello(), "Hello, my name is AN-2178!" );
  } );

  QUnit.test( "Basic conversation", function( assert ) {
    // ...
    assert.strictEqual(
      this.android.answer( "Nice to meet you!" ), "Nice to meet you too!"
    );
  } );

  QUnit.test( "Move left arm", function ( assert ) {
    // Move the left arm of the android to point (10, 50)
    this.android.moveLeftArmTo( 10, 50 );

    assert.deepEqual( this.android.getLeftArmPosition(), { x: 10, y: 50 } );
  } );

  QUnit.test( "Move right arm", function ( assert ) {
    // Move the right arm of the android to point (15, 45)
    this.android.moveRightArmTo( 15, 45 );

    assert.deepEqual( this.android.getRightArmPosition(), { x: 15, y: 45 } );
  } );

  QUnit.test( "Grab things", function ( assert ) {
    // Move the arm of the android to point (10, 50)
    this.android.grabThingAt( 25, 5 );

    assert.deepEqual( this.android.getPosition(), { x: 25, y: 5 } );
    assert.ok( this.android.isGrabbing() );
  } );

  QUnit.test( "Can walk", function ( assert ) {
    assert.ok( this.android.canWalk() );
  } );

  QUnit.test( "Can speak", function ( assert ) {
    assert.ok( this.android.canSpeak() );
  } );

  // ...
} );

使用 QUnit.module.todo()來標記代碼還在編寫中

QUnit.module.todo( "Robot", function( hooks ) {
  hooks.beforeEach( function() {
    this.robot = new Robot();
  } );

  QUnit.test( "Say", function( assert ) {
    // Currently, it returns undefined
    assert.strictEqual( this.robot.say(), "I'm Robot FN-2187" );
  } );

  QUnit.test( "Move arm", function ( assert ) {
    // Move the arm to point (75, 80). Currently, it throws a NotImplementedError
    assert.throws( function() {
      this.robot.moveArmTo(75, 80);
    }, /Not yet implemented/ );

    assert.throws( function() {
      assert.deepEqual( this.robot.getPosition(), { x: 75, y: 80 } );
    }, /Not yet implemented/ );
  } );

  // ...
} );

- only

QUnit.only( name, callback )
添加單獨運行的測試,阻止其餘測試代碼運行

參數 描述
name (string) 名稱
callback (function) Function to close over assertions

回調的參數: callback( assert ):

參數 描述
assert (object) 斷言方法的新的實例對象

描述

這個方法能幫助你專一於你的特殊測試單元,QUnit.only會致使運行時其餘的測試被忽略。

若是QUnit.only有多個,則只運行最先定義的那個。

當有測試代碼中大量的測試或者想要在控制檯看測試輸出時,這個方法很是有用。能夠在頁面的結果輸出頁面過濾其餘測試的輸出。

例子

如何使用 QUnit.only

QUnit.module( "robot", {
  beforeEach: function() {
    this.robot = new Robot();
  }
});

QUnit.test( "say", function( assert ) {
  assert.ok( false, "I'm not quite ready yet" );
});

QUnit.test( "stomp", function( assert ) {
  assert.ok( false, "I'm not quite ready yet" );
});

// You're currently working on the laser feature, so we run only this test
QUnit.only( "laser", function( assert ) {
  assert.ok( this.robot.laser() );
});

使用現代語法

const { test, only } = QUnit;

QUnit.module( "robot", {
  beforeEach: function() {
    this.robot = new Robot();
  }
});

test( "say", t => {
  t.ok( false, "I'm not quite ready yet" );
});

test( "stomp", t => {
  t.ok( false, "I'm not quite ready yet" );
});

// You're currently working on the laser feature, so we run only this test
only( "laser", function( t ) {
  t.ok( this.robot.laser() );
});

- skip

QUnit.skip( name )
跳過指定測試方法

參數 描述
name (string) 名稱

描述

使用這個方法替換掉QUnit.test()來跳過整個測試方法

This test’s prototype will be listed on the suite as a skipped test, ignoring the callback argument and the respective global and module’s hooks.

Example

如何使用skip方法

QUnit.module( "robot", {
  beforeEach: function() {
    this.robot = new Robot();
  }
});

QUnit.test( "say", function( assert ) {
  assert.strictEqual( this.robot.say(), "Exterminate!" );
});

// Robot doesn't have a laser method, yet, skip this test
// Will show up as skipped in the results
QUnit.skip( "laser", function( assert ) {
  assert.ok( this.robot.laser() );
});

使用現代語法

const { test, skip } = QUnit;

QUnit.module( "robot", {
  beforeEach() {
    this.robot = new Robot();
  }
});

test( "say", function( t ) {
  t.strictEqual( this.robot.say(), "Exterminate!" );
});

// Robot doesn't have a laser method, yet, skip this test
// Will show up as skipped in the results
skip( "laser", function( t ) {
  t.ok( this.robot.laser() );
});

- start

QUnit.start()

略(#TODO)

- test

QUnit.test( name, callback )
添加測試方法

參數 描述
name (string) 名稱
callback (function) Function to close over assertions

回調參數

參數 描述
assert (object) 斷言方法的新的實例對象

描述

使用QUnit.test()添加測試方法

這個assert參數包含了QUnit全部的斷言方法,使用這個參數進行斷言

若是你的回調函數返回了了一個then,可用的Promise,QUnit.test能自動幫你進行一部結果的解析。

例子

一個實際的例子,使用局部的assert參數

function square( x ) {
  return x * x;
}

QUnit.test( "square()", function( assert ) {
  var result = square( 2 );

  assert.equal( result, 4, "square(2) equals 4" );
});

使用現代語法

function square( x ) {
  return x * x;
}

const { test } = QUnit;

test( "square()", t => {
  t.equal( square( 2 ), 4, "square(2) equals 4" );
  t.equal( square( 3 ), 9, "square(3) equals 9" );
});

關於處理Promise異步返回的一個例子,例子使用的是es6的Promise而且延時了500ms

QUnit.test( "a Promise-returning test", function( assert ) {
  assert.expect( 1 );

  var thenable = new Promise(function( resolve, reject ) {
    setTimeout(function() {
      assert.ok( true );
      resolve( "result" );
    }, 500 );
  });
  return thenable;
});

接着上面的例子,QUnit.test也支持js的async方法。

function squareAfter1Second(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x * x);
    }, 1000);
  });
}

const { test } = QUnit;

test( "an async test", async t => {
  var a = await squareAfter1Second(2);
  var b = await squareAfter1Second(3);

  t.equal( a, 4 );
  t.equal( b, 9 );
  t.equal( await squareAfter1Second(5), 25 );
});

- todo

QUnit.todo( name, callback )
添加一個在運行期間至少有個失敗斷言的測試

參數 描述
name (string) 名稱
callback (function) Function to close over assertions

回調參數: callback( assert ):

參數 描述
assert (object) 斷言方法的新的實例對象

描述

可使用這個方法去測試還在開發階段的代碼。只要存在一個失敗的斷言,測試就會經過。

若是所有斷言都經過,測試後會有個失敗結果,而後應該替換成QUnit.test

例子

如何使用QUnit.todo

QUnit.module( "robot", {
  beforeEach: function() {
    this.robot = new Robot();
  }
});

// fireLazer hasn't been properly implemented yet, so this is a todo test
QUnit.todo( "fireLazer returns the correct value", function( assert ) {
  var result = this.robot.fireLazer(); // Currently returns undefined
  assert.equal( result, "I'm firing my lazer!" );
});

斷言

- async

async( [ acceptCallCount = 1 ] )

等待異步操做

參數 描述
acceptCallCount (Number) 在測試完成以前指望回調次數,默認是1

介紹

assert.async()返回一個回調函數,而且暫停測試進程直到回調方法被調用指定的次數。The callback will throw an Error if it is invoked more often than the accepted call count.

這取代了先前由QUnit.stop()和QUnit.start()提供的功能

例子

讓QUnit等待定時器裏的done方法調用(#TODO,之後不肯定的就用#TODO)

QUnit.test( "assert.async() test", function( assert ) {
  var done = assert.async();
  var input = $( "#test-input" ).focus();
  setTimeout(function() {
    assert.equal( document.activeElement, input[0], "Input was focused" );
    done();
  });
});

爲了每個操做assert.async(),每個done回調被調用至多一次

QUnit.test( "two async calls", function( assert ) {
  assert.expect( 2 );

  var done1 = assert.async();
  var done2 = assert.async();
  setTimeout(function() {
    assert.ok( true, "test resumed from async operation 1" );
    done1();
  }, 500 );
  setTimeout(function() {
    assert.ok( true, "test resumed from async operation 2" );
    done2();
  }, 150);
});

設置異步測試三個退出點。 每一個done()調用都會累加到acceptCallCount。 三次調用後,測試完成

QUnit.test( "multiple call done()", function( assert ) {
  assert.expect( 3 );
  var done = assert.async( 3 );

  setTimeout(function() {
    assert.ok( true, "first call done." );
    done();
  }, 500 );

  setTimeout(function() {
    assert.ok( true, "second call done." );
    done();
  }, 500 );

  setTimeout(function() {
    assert.ok( true, "third call done." );
    done();
  }, 500 );
});

- deepEqual

深度遞歸比較,處理原始類型,數組,對象,正則表達式,日期和函數

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

介紹

若是是判斷兩個對象相不相等,好比說像這樣子的,{ key: value } 等於 { key: value }。deepEqual斷言能夠像equal()那樣子去使用。對於non-scalar values、identity會被deepEqual無視

notDeepEqual()可用於顯式測試深度,嚴格的不等式

例子

比較兩個對象

QUnit.test( "deepEqual test", function( assert ) {
  var obj = { foo: "bar" };

  assert.deepEqual( obj, { foo: "bar" }, "Two objects can be the same in value" );
});

- equal

equal( actual, expected [, message ] )

不嚴格比較,大體至關於JUnit的assertEquals。

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

equal斷言用來簡單比較actual和expected這兩個參數,跟操做符(==)類似。若是相等,則斷言經過;不然就失敗。若是失敗了,actual和expected這兩個值會展現在測試結果上。除了給定的消息。

notEqual用來判斷不相等。

strictEqual用來判斷嚴格相等。

例子

簡單的斷言例子

QUnit.test( "a test", function( assert ) {
  assert.equal( 1, "1", "String '1' and number 1 have the same value" );
});

一組稍微完全點的斷言

QUnit.test( "equal test", function( assert ) {
  assert.equal( 0, 0, "Zero, Zero; equal succeeds" );
  assert.equal( "", 0, "Empty, Zero; equal succeeds" );
  assert.equal( "", "", "Empty, Empty; equal succeeds" );

  assert.equal( "three", 3, "Three, 3; equal fails" );
  assert.equal( null, false, "null, false; equal fails" );
});

- expect

expect( amount )

指定在測試中會有多少個斷言

參數 描述
actual 斷言的數量

描述

確保在任何運行中的測試的準確斷言的數量,用assert.expert(number)註冊斷言的數量。若是運行測試後斷言數量與註冊的斷言數量不匹配,則不經過測試

例子

聲明斷言數量

QUnit.test( "a test", function( assert ) {
  assert.expect( 2 );

  function calc( x, operation ) {
    return operation( x );
  }

  var result = calc( 2, function( x ) {
    assert.ok( true, "calc() calls operation function" );
    return x * x;
  });

  assert.equal( result, 4, "2 squared equals 4" );
});

- notDeepEqual

notDeepEqual( actual, expected [, message ] )

深度遞歸比較差別(與deepEqual相反,一個判相同,一個判不一樣),處理原始類型,數組,對象,正則表達式,日期和函數

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

若是是判斷兩個對象相不相等,好比說像這樣子的,{ key: value } 等於 { key: value }。notDeepEqual斷言能夠像equal()那樣子去使用。對於non-scalar values、identity會被notDeepEqual無視

deepEqual()可用於顯式測試深度,嚴格的相等式

例子

比較兩個對象

QUnit.test( "notDeepEqual test", function( assert ) {
  var obj = { foo: "bar" };

  assert.notDeepEqual( obj, { foo: "bla" }, "Different object, same key, different value, not equal" );
});

- notEqual

notEqual( actual, expected [, message ] )

不嚴格比較,用來判斷不等

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

notEqual斷言用來簡單比較actual和expected這兩個參數,跟操做符(!=)類似。若是不相等,則斷言經過;不然就失敗。若是失敗了,actual和expected這兩個值會展現在測試結果上,除了給定的消息。

equal用來判斷相等

notStrictEqual()用來判斷嚴格不相等

例子

簡單的例子

QUnit.test( "a test", function( assert ) {
  assert.notEqual( 1, "2", "String '2' and number 1 don't have the same value" );
});

- notOk

notOk( state [, message ] )

和ok()和CommonJS的assert.ok()相反,與JUnit的assertFalse等價。第一個參數爲false就經過測試

參數 描述
state 測試的值
message(string) 描述

描述

notOk()只須要一個參數。若是參數爲false,則測試經過;不然就失敗。若是提供了第二個參數,會在結果那裏展現出來。

例子

QUnit.test( "notOk test", function( assert ) {
  assert.notOk( false, "false succeeds" );
  assert.notOk( "", "empty string succeeds" );
  assert.notOk( NaN, "NaN succeeds" );
  assert.notOk( null, "null succeeds" );
  assert.notOk( undefined, "undefined succeeds" );

  assert.notOk( true, "true fails" );
  assert.notOk( 1, "1 fails" );
  assert.notOk( "not-empty", "not-empty string fails" );
});

- notPropEqual

notPropEqual( actual, expected [, message ] )

嚴格比較對象的屬性,判斷不相等則經過測試

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

notPropEqual斷言用來嚴格判斷對象的屬性相不相等,並非constructors。不相等測試就經過。

例子

比較兩個對象的屬性相不相等

QUnit.test( "notPropEqual test", function( assert ) {
  function Foo( x, y, z ) {
    this.x = x;
    this.y = y;
    this.z = z;
  }
  Foo.prototype.doA = function () {};
  Foo.prototype.doB = function () {};
  Foo.prototype.bar = 'prototype';

  var foo = new Foo( 1, "2", [] );
  var bar = new Foo( "1", 2, {} );
  assert.notPropEqual( foo, bar, "Properties values are strictly compared." );
});

- notStrictEqual

notStrictEqual( actual, expected [, message ] )

嚴格比較相不相等

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

notStrictEqual斷言用來簡單比較actual和expected這兩個參數,跟操做符(!==)類似。若是不相等,則斷言經過;不然就失敗。若是失敗了,actual和expected這兩個值會展現在測試結果上。除了給定的消息。

strictEqual()用來嚴格判斷相等

例子

簡單的例子

QUnit.test( "a test", function( assert ) {
  assert.notStrictEqual( 1, "1", "String '1' and number 1 have the same value but not the same type" );
});

- ok

ok( state [, message ] )

等價於CommonJS的assert.ok()和JUnit的assertTrue().state參數爲true,則則是經過。

參數 描述
state 測試的值
message(string) 描述

描述

在QUnit中最基礎的斷言,只須要一個參數。若是個爲true,則測試經過,若是爲false,則測試失敗。若是提供了第二個參數msg,msg則會顯示在測試結果上。

例子

QUnit.test( "ok test", function( assert ) {
  assert.ok( true, "true succeeds" );
  assert.ok( "non-empty", "non-empty string succeeds" );

  assert.ok( false, "false fails" );
  assert.ok( 0, "0 fails" );
  assert.ok( NaN, "NaN fails" );
  assert.ok( "", "empty string fails" );
  assert.ok( null, "null fails" );
  assert.ok( undefined, "undefined fails" );
});

- propEqual

propEqual( actual, expected [, message ] )

比較對象的屬性

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

propEqual斷言判斷對象的屬性,相等則經過,不相等則不經過。跟操做符(===)相似。不一樣於deppEqual,propEqual使用來判斷對象的屬性和constructors相不相等的。

例子

比較兩個對象的屬性

QUnit.test( "propEqual test", function( assert ) {
  function Foo( x, y, z ) {
    this.x = x;
    this.y = y;
    this.z = z;
  }
  Foo.prototype.doA = function () {};
  Foo.prototype.doB = function () {};
  Foo.prototype.bar = 'prototype';

  var foo = new Foo( 1, "2", [] );
  var bar = {
    x : 1,
    y : "2",
    z : []
  };
  assert.propEqual( foo, bar, "Strictly the same properties without comparing objects constructors." );
});

- pushResult

pushResult( data: { result, actual, expected, message } )

報告自定義斷言的結果

參數 描述
data.result (boolean) 斷言的結果
data.actual 測試的值
data.expected 指望的值
data.message(string) 描述

描述

某些測試套件可能須要表達QUnit的任何內置斷言未定義的指望。能夠經過將指望封裝在JavaScript函數中來知足此需求(#TODO),該JavaScript函數返回布爾值。而後將此值傳遞給ok()斷言

A more readable solution would involve defining a custom assertion. If the expectation function invokes pushResult, QUnit will be notified of the result and report it accordingly.

例子

定義自定義斷言mod2,在modulo2,若是提供的參數是等價的則經過。

QUnit.assert.mod2 = function( value, expected, message ) {
    var actual = value % 2;
    this.pushResult( {
        result: actual === expected,
        actual: actual,
        expected: expected,
        message: message
    } );
};

QUnit.test( "mod2", function( assert ) {
    assert.expect( 2 );

    assert.mod2( 2, 0, "2 % 2 == 0" );
    assert.mod2( 3, 1, "3 % 2 == 1" );
});

- rejects

rejects( promise, expectedMatcher )

Test if the provided promise rejects, and optionally compare the rejection value.

參數 描述
promise (thenable) 返回的rejects
expectedMatcher 比較Reject值的方法
message (string) 描述

描述

當測試代碼基於一組特定的環境想要返回rejects時,使用assert.rejects()測試並比較

expectedMatcher方法的參數能夠是

  • 斷言經過時返回true的方法
  • 錯誤對象
  • A base constructor to use ala rejectionValue instanceof expectedMatcher
  • 匹配 rejectionValue.toString()

的正則

提示:爲了不把 message 和 expectedMatcher搞混了,expectedMatcher不能是string

例子

糾正錯誤信息的斷言收到自定義錯誤對象(#TODO)

QUnit.test( "rejects", function( assert ) {

  assert.rejects(Promise.reject("some error description"));

  assert.rejects(
    Promise.reject(new Error("some error description")),
    "rejects with just a message, not using the 'expectedMatcher' argument"
  );

  assert.rejects(
    Promise.reject(new Error("some error description")),
    /description/,
    "`rejectionValue.toString()` contains `description`"
  );

  // Using a custom error like object
  function CustomError( message ) {
    this.message = message;
  }

  CustomError.prototype.toString = function() {
    return this.message;
  };

  assert.rejects(
    Promise.reject(new CustomError()),
    CustomError,
    "raised error is an instance of CustomError"
  );

  assert.rejects(
    Promise.reject(new CustomError("some error description")),
    new CustomError("some error description"),
    "raised error instance matches the CustomError instance"
  );

  assert.rejects(
    Promise.reject(new CustomError("some error description")),
    function( err ) {
      return err.toString() === "some error description";
    },
    "raised error instance satisfies the callback function"
  );
});

- step

step( [ message ] )

給定測試的進度標記

參數 描述
message (string) 描述

描述

step一般都會經過不報錯的,除非你傳的參數不是string類型或者沒傳參數。step使用提供的消息註冊測試中的斷言。這使得開發者容易檢查執行中代碼的關鍵點,特別是在異步測試的時候和使用verifySteps的時候。

與verifySteps一塊兒使用的時候,step斷言幫你驗證代碼執行的順序和執行次數

例子

QUnit.test( "step test", function( assert ) {
  assert.expect( 1 );
  obj.hook = function() {
    assert.step('Hook is called!');
  };
  obj.invokeHookIndirectly();
});
提示:查看verifySteps,知道更多內容和例子

- strictEqual

strictEqual( actual, expected [, message ] )

嚴格類型、值的比較

參數 描述
actual 測試的值
expected 已知被比較的值
message(string) 描述

描述

提供嚴格的類型、值的比較。與操做符(===)等價

例子

QUnit.test( "strictEqual test", function( assert ) {
  assert.strictEqual( 1, 1, "1 and 1 have the same value and type" );
}); 

- throws

throws( blockFn, expectedMatcher )

Test if a callback throws an exception, and optionally compare the thrown error.

參數 描述
blockFn (function) 執行的方法
expectedMatcher 錯誤處理方法
message(string) 描述

描述

當測試代碼基於一組特定的環境指望拋出錯誤時,使用assert.throws()捕捉錯誤對像並比較是否相同。

expectedMatcher的參數

  • 錯誤對象
  • An Error constructor to use ala errorValue instanceof expectedMatcher
  • 匹配錯誤提示的正則
  • 必須返回true的回調以經過測試
  • 在極少數的環境下,像Closure Compiler,異常信息是不返回的而且會由於發生錯誤而中斷。對於這種狀況,別名被捆綁稱爲引起。 它具備相同的簽名和行爲,只是一個不一樣的名稱。(#TODO)

例子

糾正錯誤信息的斷言收到自定義錯誤對象(#TODO)

QUnit.test( "throws", function( assert ) {

  function CustomError( message ) {
    this.message = message;
  }

  CustomError.prototype.toString = function() {
    return this.message;
  };

  assert.throws(
    function() {
      throw "error"
    },
    "throws with just a message, not using the 'expected' argument"
  );

  assert.throws(
    function() {
      throw new CustomError("some error description");
    },
    /description/,
    "raised error message contains 'description'"
  );

  assert.throws(
    function() {
      throw new CustomError();
    },
    CustomError,
    "raised error is an instance of CustomError"
  );

  assert.throws(
    function() {
      throw new CustomError("some error description");
    },
    new CustomError("some error description"),
    "raised error instance matches the CustomError instance"
  );

  assert.throws(
    function() {
      throw new CustomError("some error description");
    },
    function( err ) {
      return err.toString() === "some error description";
    },
    "raised error instance satisfies the callback function"
  );
});

- timeout

timeout( duration )

(#TODO)

描述

(#TODO)

例子

QUnit.test( "Waiting for focus event", function( assert ) {
  assert.timeout( 1000 ); // Timeout of 1 second
  var done = assert.async();
  var input = $( "#test-input" ).focus();
  setTimeout(function() {
    assert.equal( document.activeElement, input[0], "Input was focused" );
    done();
  });
});

--

QUnit.test( "Waiting for async function", function( assert ) {
  assert.timeout( 500 ); // Timeout of .5 seconds
  var promise = asyncFunction();
  return promise.then( function( result ) {
    assert.ok( result );
  } );
});

--

QUnit.test( "Waiting in an async test", async assert => {
  assert.timeout( 500 ); // Timeout of .5 seconds

  let result = await asyncFunction();
  assert.ok( result );
});

- verifySteps

verifySteps( steps [, message ] )

(#TODO)

描述

(#TODO)

例子

(#TODO)

QUnit.test( "user-defined hooks execute in correct order", function( assert ) {
  let lastStep = 'none';
  let startCount = 0;
  let middleCount = 0;
  let endCount = 0;

  obj.start = function() {
    assert.equal(lastStep, 'none');
    lastStep = 'start';
    startCount++;
  };
  obj.middle = function() {
    assert.equal(lastStep, 'start');
    lastStep = 'middle';
    middleCount++;
  };
  obj.end = function() {
    assert.equal(lastStep, 'middle');
    endCount++;
  };

  return obj.process().then(function() {
    assert.equal(startCount, 1);
    assert.equal(middleCount, 1);
    assert.equal(endCount, 1);
  });
});

(#TODO)

QUnit.test( "user-defined hooks execute in correct order", function( assert ) {
  obj.start = function() {
    assert.step('start');
  };
  obj.middle = function() {
    assert.step('middle');
  };
  obj.end = function() {
    assert.step('end');
  };

  return obj.process().then(function() {
    assert.verifySteps(['start', 'middle', 'end']);
  });
});

(#TODO)

QUnit.test( "subscribe/unsubscribe", function( assert ) {

  const publisher = new Publisher();
  const messages = [];

  const subscriber1 = message => messages.push(`Subscriber #1: ${message}`);
  const subscriber2 = message => messages.push(`Subscriber #2: ${message}`);

  publisher.subscribe(subscriber1);
  publisher.subscribe(subscriber2);

  publisher.publish('Hello!');

  publisher.unsubscribe(subscriber1);

  publisher.publish('World!');

  assert.deepEqual(messages, [
    'Subscriber #1: Hello!',
    'Subscriber #2: Hello!',
    'Subscriber #2: World!'
  ]);
});

(#TODO)

QUnit.test( "subscribe/unsubscribe", function( assert ) {

  const publisher = new Publisher();

  const subscriber1 = message => assert.step(`Subscriber #1: ${message}`);
  const subscriber2 = message => assert.step(`Subscriber #2: ${message}`);

  publisher.subscribe(subscriber1);
  publisher.subscribe(subscriber2);

  publisher.publish('Hello!');

  publisher.unsubscribe(subscriber1);

  publisher.publish('World!');

  assert.verifySteps([
    'Subscriber #1: Hello!',
    'Subscriber #2: Hello!',
    'Subscriber #2: World!'
  ]);
});

(#TODO)

QUnit.test( "verify steps", function test(assert){
    assert.expect( 5 );

    assert.step( "do stuff 1" );
    assert.step( "do stuff 2" );
    assert.verifySteps( [ "do stuff 1", "do stuff 2" ] );

    assert.step( "do stuff 3" );
    assert.verifySteps( [ "do stuff 3" ] );
} );
相關文章
相關標籤/搜索