Как проверить функцию, которая выдает ошибку асинхронно, используя ленту?

Я пытаюсь проверить этот модуль (receiver.js) на предмет ошибки:

var request = require('request')

module.exports = function(url){
    request({
        url: url,
        method: 'POST'
    }, function(error) {
        if(error){
            throw error
        }
    })
}

используя этот тест (test.js):

var test = require('tape')

test('Receiver test', function(t){
    var receiver = require('./receiver')
    t.throws(function(){
        receiver('http://localhost:9999') // dummy url
    }, Error, 'Should throw error with invalid URL')
    t.end()
})

но лента запускает утверждение до появления ошибки, что приводит к следующему сообщению об ошибке:

TAP version 13  
# Receiver test  
not ok 1 Should throw error with invalid URL  
  ---  
    operator: throws  
    expected: |-  
      [Function: Error]  
    actual: |-  
      undefined  
    at: Test.<anonymous> (/path/to/tape-async-error-test/test.js:5:4)  
  ...  
/path/to/receiver.js:9  
throw error  
^  

Error: connect ECONNREFUSED 127.0.0.1:9999  
    at Object.exports._errnoException (util.js:856:11)  
    at exports._exceptionWithHostPort (util.js:879:20)  
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)  

Это можно обойти?

0 ответов

Как правило, используя ленту, вы должны убедиться, что вы звоните assert.end() после завершения асинхронного вызова. Использование обещаний (потребует request-promise и возвращая обещание)

test('Receiver test', function(t){
    // Tells tape to expec a single assertion
    t.plan(1);

    receiver('http://localhost:9999')
        .then(() => {
            t.fail('request should not succeed')
        })
        .catch(err => {
            t.ok(err, 'Got expected error');
        })
        .finally({
            t.end();
        });
});

С помощью async/await:

test('Receiver test', async function(t) {
    try {
        await receiver('http://localhost:9999');
        assert.fail('Should not get here');
    } catch (err) {
        assert.ok(err, 'Got expected error');
    }
    t.end();
});

Приведенный выше пример в основном верен, но вот полный рабочий пример, в котором асинхронный и синхронный сравнивается бок о бок, а также показано, как проверить сообщение об ошибке, аналогично примерам ленты, приведенным на ленте README.md.

test('ensure async function  can be tested to throw', async function(t) {
  // t.throw works synchronously
  function normalThrower() {
    throw(new Error('an artificial synchronous error'));
  };
  t.throws(function () { normalThrower() }, /artificial/, 'should be able to test that a normal function throws an artificial error');

  // you have to do this for async functions, you can't just insert async into t.throws
  async function asyncThrower() {
    throw(new Error('an artificial asynchronous error'));
  };  
  try {
    await asyncThrower();
    t.fail('async thrower did not throw');
  } catch (e) {
    t.match(e.message,/asynchronous/, 'asynchronous error was thrown');
  };
});

Другие вопросы по тегам