将摩卡“done()”转换为“done()”测试“异步”当“完成()”时在内部函数中调用
我想在下面的测试中添加对同步函数的调用:
describe('the server', function() {
it('should respond to a udp packet', function(done) {
// TODO: call async function here
const udp = dgram.createSocket('udp4');
udp.on('error', function(error) {
console.log(error);
});
udp.on('message', function(msg, rinfo) {
console.log('msg', msg);
console.log('rinfo', rinfo);
// TODO: check the reply
udp.close();
done();
});
udp.bind();
// send a request
const bytes = Buffer.from("421a0800117860bc457f0100001a0653455256455222054d54303031", 'hex');
udp.send(bytes, SERVER_PORT, SERVER_ADDR)
});
});
如果我只是添加 async
, 来使:
it('should respond to a udp packet', async function(done) {
我收到错误:
1) the server
should respond to a udp packet:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
但我需要 done
作为仅当从服务器收到数据包时测试才结束。
有没有一种方法只能从内部函数内部的异步函数“返回”?
I would like to add a call to a sync function to the test below:
describe('the server', function() {
it('should respond to a udp packet', function(done) {
// TODO: call async function here
const udp = dgram.createSocket('udp4');
udp.on('error', function(error) {
console.log(error);
});
udp.on('message', function(msg, rinfo) {
console.log('msg', msg);
console.log('rinfo', rinfo);
// TODO: check the reply
udp.close();
done();
});
udp.bind();
// send a request
const bytes = Buffer.from("421a0800117860bc457f0100001a0653455256455222054d54303031", 'hex');
udp.send(bytes, SERVER_PORT, SERVER_ADDR)
});
});
If I just add async
, to make:
it('should respond to a udp packet', async function(done) {
I get an error:
1) the server
should respond to a udp packet:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
but I need the done
as the test is only over when a packet is received from the server.
Is there a way of only "returning" from an async function from within an inner function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里至少有两种方法:使用异步调用返回的 Promise 或使整个测试函数异步。我将展示第二种方法,因为在不知道待办事项中的异步函数调用是什么样子的情况下,它更容易实现。
基本上需要完成三项更改:
done
参数。done
回调的语句或语句组包装在 Promise 中。如果您想保留该名称,请将 Promise 回调的第一个参数命名为done
。这对于测试来说应该足够了。为了更准确地处理错误,您可能希望在出现异常时拒绝承诺:
There are at least two approaches here: work with the promise returned by the async call or make the whole test function async. I'm going to show the second method becuase it's easier to implement without knowing how the async function call in the todo looks like.
There are basically three changes to be done:
done
parameter.done
callback in a promise. Name the first parameter of the promise callbackdone
if you want to keep that name.This should be sufficient for a test. For a more accurate error handling you may want to reject the promise in case of an exception:
您还可以使用 mocha --exit ,这比您自己清理要简单得多。
You can also use
mocha --exit
which is far simpler than cleaning up after yourself.