assert.pushResult()

添加的版本:1.22.0

說明

pushResult( data )

報告自定義斷言的結果。

名字 說明
data.result(布爾值) 斷言的結果
data.actual 正在測試的表達式
data.expected 已知比較值
data.message(字符串) 斷言的簡短說明

例子

如果您需要表達一個未被 QUnit 內置斷言抽象的期望,您可以執行自己的臨時邏輯,然後將兩個直接可比較的值傳遞給 assert.strictEqual() ,或者將您自己的代表性布爾結果傳遞給 assert.true() .

QUnit.test('bad example with remainder', assert => {
  const result = 3;
  const actual = (result % 2) === 1;
  assert.true(actual, 'remainder of mod 2 is 1');
  // In case of failure, there is no information about the
  // actually observed remainder or the expected value
});

QUnit.test('good example with remainder', assert => {
  const result = 3;
  assert.strictEqual(result % 2, 1, 'remainder of mod 2');
});

QUnit.test('example with value in range', assert => {
  const actual = 3;
  const isBetween = (actual >= 1 && actual <= 10);
  assert.true(isBetween, 'result between 1 and 10');
  // No information in case of failure.
  // Cannot be expressed in a useful way using strictEqual()
  //
  // Example of failure if result is out of range:
  // > actual: false
  // > expected: true
});

自定義斷言

使用自定義斷言方法,您可以控製應如何評估斷言,與在發生故障時如何說明其實際值和預期值分開。

例如:

QUnit.assert.between = function (actual, from, to, message) {
  const isBetween = (actual >= from && actual <= to);

  this.pushResult({
    result: isBetween,
    actual: actual,
    expected: `between ${from} and ${to} inclusive`,
    message: message
  });
};

QUnit.test('custom assertion example', assert => {
  const result = 3;
  assert.between(result, 1, 10, 'result');
  // Example of failure if result is out of range
  // > actual: 42
  // > expected: between 1 and 10
});