简体   繁体   English

如何在Promise承诺的范围内使Node单元测试失败?

[英]How do I fail a Node unit test on the catch of a Promise?

I'm doing some unit tests using Node.js and I want to fail a test like this: 我正在使用Node.js进行一些单元测试,但我想通过这样的测试失败:

doSomething()
    .then(...)
    .catch(ex => {
        // I want to make sure the test fails here
    });

I'm using Assert, so I found Assert.Fails . 我正在使用Assert,所以我找到了Assert.Fails The problem is that fails expects actual and expected , which I don't have. 问题是, fails期望的是actualexpected ,而我没有。 The Node documentation doesn't say anything about them being required, but the Chai documentation , which is Node compliant, say they are. Node文档没有说明它们是必需的,但是说符合Node的Chai文档

How should I fail a test on the catch of a promise? 我应该如何失败的测试catch一个承诺吗?

You can use a dedicated spies library, like Sinon , or you can implement a simple spy yourself. 您可以使用专用的间谍库,例如Sinon ,也可以自己实现一个简单的间谍程序。

function Spy(f) {
  const self = function() {
    self.called = true;
  };
  self.called = false;
  return self;
}

The spy is just a wrapper function which records data about how the function has been called. 间谍只是一个包装函数,它记录有关如何调用该函数的数据。

const catchHandler = ex => ...;
const catchSpy = Spy(catchHandler);

doSomething()
  .then(...)
  .catch(catchSpy)
  .finally(() => {
    assert.ok(catchSpy.called === false);
  });

The basic principle is to spy on the catch callback, then use the finally clause of your promise to make sure that the spy hasn't been called. 基本原理是监视catch回调,然后使用promise的finally子句确保未调用间谍。

Have you considered Assert.Ok(false, message)? 您是否考虑过Assert.Ok(false,message)? It's more terse. 更简洁。

Assert.fail is looking to do a comparison and display additional info. Assert.fail希望进行比较并显示其他信息。

If you will use mocha , then elegant way would be as following: 如果您将使用mocha ,那么优雅的方式如下:

describe('Test', () => {
  it('first', (done) => {
    doSomething()
    .then(...)
    .catch(done) 
    })
})

If your Promise fail, done method will be invoked with the thrown exception as a parameter, so code above is equivalent to 如果您的Promise失败,将使用抛出的异常作为参数来调用done方法,因此上面的代码等效于

catch(ex => done(ex))

In mocha invoking done() with the parameter fails the test. mocha ,使用参数调用done()会使测试失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM