gpt4 book ai didi

node.js - 如何使用磁带测试异步抛出错误的函数?

转载 作者:搜寻专家 更新时间:2023-10-31 22:35:24 24 4
gpt4 key购买 nike

我正在尝试测试此模块 (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)

有解决办法吗?

最佳答案

通常,使用磁带时,您必须确保在异步调用完成后调用 assert.end()。使用 promise (需要 request-promise 并返回 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();
});

关于node.js - 如何使用磁带测试异步抛出错误的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35135830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com