简体   繁体   中英

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:

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

I'm using Assert, so I found Assert.Fails . The problem is that fails expects actual and expected , which I don't have. The Node documentation doesn't say anything about them being required, but the Chai documentation , which is Node compliant, say they are.

How should I fail a test on the catch of a promise?

You can use a dedicated spies library, like Sinon , or you can implement a simple spy yourself.

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.

Have you considered Assert.Ok(false, message)? It's more terse.

Assert.fail is looking to do a comparison and display additional info.

If you will use mocha , then elegant way would be as following:

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

catch(ex => done(ex))

In mocha invoking done() with the parameter fails the test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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