【问题标题】:How to let test fail on console.assert failure with Jasmine?如何让 Jasmine 的 console.assert 失败测试失败?
【发布时间】:2021-12-08 09:48:43
【问题描述】:

我们确实在我们的代码库as part of defensive programming 中使用console.assert 来检查一些复杂的代码部分并注释关于代码中正在执行的操作/它计算/假设的值等的假设。

例子:

function calculateSomething(a, b, c) {
  // assume, we know that the calculation result below should never be negative, because other logic assures that (b - c) < a (This is just an example.)
  // or that check is implemented here, but just to make sure you put that negative check before returning the value
  const result = a - (b - c);
  console.assert(result > 0, 'result must not be negative, but was', result);
  return result;
}

console.log('result 1:', calculateSomething(1, 2, 3)); // fails
console.log('result 2:', calculateSomething(1, 3, 2)); // works

现在,我们注意到这只会在生产代码/通常代码运行时在控制台中失败/打印错误消息,但在测试执行代码时明确不会

如何让console.assert 在测试中也失败?

【问题讨论】:

    标签: javascript console jasmine assert


    【解决方案1】:

    好的,我想你可以存根它,因为它可能有用,请保留the original callThrough in addition to callFake。只需将其放入您的 beforeEach 中,您的测试就会尊重 console.assert 并将其视为失败:

    打字稿版本:

    const realConsoleAssert = console.assert;
    assertSpy = spyOn(console, 'assert').and.callFake((assertion: any, message?: string, ...optionalParams: any[]) => {
      realConsoleAssert(assertion, message, ...optionalParams);
      expect(assertion).toBeTruthy(`${message} ${optionalParams.concat(' ')}`);
    });
    

    JavaScript 版本:

    const realConsoleAssert = console.assert;
    assertSpy = spyOn(console, 'assert').and.callFake((assertion, message, ...optionalParams) => {
      realConsoleAssert(assertion, message, ...optionalParams);
      expect(assertion).toBeTruthy(`${message} ${optionalParams.concat(' ')}`);
    });
    

    尤其是optionalParams 还不够理想,也没有像console.assert 那样优雅地对待它,例如undefined 被转换为一个空字符串,而浏览器版本会正确打印它,但这只是一个小细节恕我直言。

    这个could be simplified with a custom spy strategy though

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 2013-12-12
      • 2016-08-22
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多