Jest/SuperTest 如何在一组承诺中正确预期套接字挂断?

问题描述

我有一个测试说“在大约 X 个并发连接之后,我应该看到套接字挂断,因为我的服务将停止回答某人的问题。”

经过大量痛苦的反复试验后,这很有效,但是因为我正在使用 await Promise.all(myrequests) 我第一次看到挂断时会抛出 socket hang up 异常。

这可行,但会导致一些错误消息,因为我的挂断例程会进行一些调试日志记录,此时测试已经结束。

最好的说法是:“等待所有这些,即使它们抛出错误?”

我的笑话/超级测试问题块看起来像:

 //Send enough concurrent connections to trip the dropout
 for(var i = 0;MAX_CONCURRENT_CONNECTIONS+5;i++) 
    {
       requests.push(request(app).get('/'))   
    }
    //wait for all the connections to resolve    
    const t = async () => {          
       await Promise.all(requests);                    
    };
    //and make sure some drop off
    expect(t).toThrow("socket hang up"); //this also doesn't match the error string right but that is because I'm not as experienced in this sort of thing as I'd like!

    //however after this,the test ends,and my back end logging causes problems since the test is over!

即使抛出 await Promise.all(requests),仍然等待请求中的所有 promise 的最佳方法是什么?

我可以做以下丑陋的代码,但我正在寻找正确的方法来编写它:)

        let gotConnReset = false
        try
        {
           await Promise.all(requests);                                    
        }
        catch(err)
        {
            if(err.message == "socket hang up")
            {
                gotConnReset = true;
            }            
        }
        assert(gotConnReset === true);
        //wait for all the other requests so that Jest doesn't yell at us!
        await Promise.allSettled(requests); 

解决方法

我不知道 Jest 有什么帮助,但是 Promise.allSettled 将等待所有承诺履行或拒绝,返回所有结果的数组。被拒绝的承诺将附加一个 .reason

主要区别在于 Jest 将匹配错误对象而不是使用抛出的错误匹配器,因此某些特定于错误的功能不存在。

test('allSettled rejects',async () => {
  class Wat extends Error {}
  const resError = new Wat('Nope')
  resError.code = 'NO'
  const res = await Promise.allSettled([
    Promise.resolve(1),Promise.reject(resError),Promise.resolve(3),])
  expect(res).toEqual(
    expect.arrayContaining([
      { status: 'rejected',reason: new Error('Nope') },])
  )
})
  ✓ allSettled rejects (2 ms)

如果你想避免上面例子的“松散”匹配,如果 Error 匹配,它可能需要与任何 message 对象一起传递,它可能需要类似 jest-matcher-specific-error 或 {{ 1}} 错误匹配器

结果可以使用 expect.extend/filtermap 直接测试拒绝。

reduce

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...