Jasmine期望投掷,既不传球也不接球

Jasmine expect toThrow not passing nor catching

本文关键字:期望 Jasmine      更新时间:2023-09-26

尝试在量角器中使用expect(fn).toThrow()

我传递的函数(fn)返回一个promise(protractor.promise.defer(,量角器应该强制expect()正确处理它。

在运行时,它没有捕获错误和/或通过测试,而是既不也不

  • "需要函数来引发错误">
  • "等待约3000ms后超时">
    • (由browser.wait()的超时参数引发(

我已尝试使用:

  • 抛出可捕获错误的deferred.reject()
    • 通常通过在有希望的函数上使用.thenCatch()而不是.then()来捕获
  • deferred.fulfill()并在函数中"手动"抛出错误
    • 使用语法throw new Error();
    • throw {name: 'Error', message: 'timed out'}
    • throw {name: 'Exception'}
  • 我已经尝试删除.fulfill().reject(),这意味着期望继续前进的唯一方法就是抛出错误
  • 我甚至删除了所有的return语句,所以expect不会完成函数,除非它抛出错误
  • 更新:尝试使用.toThrowError()而不是.toThrow()
  • Update:尝试通过自定义匹配器覆盖.toThrow(),但我不知道如何使.thenCatch()中的匿名函数使原始匹配器返回其result对象而不返回promise

Everytime预期失败并且错误仍然被抛出和未被捕获(正如语法所说的将被抛出(。

我的预感是:

  • 对于这种情况,量角器是否未正确覆盖expect
  • 是因为throw发生在传递给.then(function(){ /*error thrown here*/ })的匿名函数中,而不是原始的fn函数中吗
  • 我可以让茉莉花定制火柴盒承诺稍后返回结果吗?(量角器也解释了这些承诺吗?(然后我会覆盖原始的.toThrow()方法来解释这种可能性
  • 还是我只是忽略了一些简单的东西

假设您的承诺稍后会被实现/拒绝(async(,那么在这种情况下,您不能依赖expect(function() {..}.toThrow()来工作。

我会做的是这样的事情(不习惯量角器的承诺(:

it('.....', function(done) {
    MyPromise(...)
        .then(... my normal process which should throw....)
        .then(function() { 
                   // Error not thrown by the process, so fail the test.
                   expect(true).toBe(false);
              },
              function(err) {
                   // Expected error thrown so pass the test.
                   done();
              });
});

假设这就是你捕捉量角器承诺错误的方式?

其他一些实现有一个.catch()方法可以链接。

Chai as Promised可能有助于拥有更干净的语法,例如:

expect(fn_returning_promise()).to.eventually.be.rejectedWith(...)