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
});