由 AWS SDK 导致的环境被破坏后尝试导入的笑话

Posted

技术标签:

【中文标题】由 AWS SDK 导致的环境被破坏后尝试导入的笑话【英文标题】:Jest trying to import after environment torn down, caused by AWS SDK 【发布时间】:2021-10-02 03:55:57 【问题描述】:

我的应用程序的 Jest 集成测试在本地 DynamoDB 中创建记录,所有测试都顺利通过,但在之后的清理中,我收到一条消息说

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at Object.userAgent (node_modules/aws-sdk/lib/util.js:34:43)
      at HttpRequest.setUserAgent (node_modules/aws-sdk/lib/http.js:111:78)
      at new HttpRequest (node_modules/aws-sdk/lib/http.js:104:10)
      at new Request (node_modules/aws-sdk/lib/request.js:328:24)
      at features.constructor.makeRequest (node_modules/aws-sdk/lib/service.js:202:19)
npm ERR! Test failed.  See above for more details.

我有一个 afterAll 设置在每次测试后运行并删除创建的记录,如下所示:

afterAll(async () => 
    ECs.forEach(async (EC) => 
        await deleteUser(EC);
    )
    ECs = []; 
)

我尝试使用假计时器但没有成功。这些测试也都是按顺序运行的。这是其中一项测试的示例:

test("Create new user", async () => 
    const johnECInitialRequestParams = 
        EC: 
            firstName: "John",
            email: "john.smith@gmail.com",
        ,
        responsibleFor: "8b8a9eb9-840f-4245-9200-719fe05f6612"
    

    const johnECResultStoredObject = 
        ECID: "f576d1cb-4df0-4093-9b2d-b94c70a28e18",
        firstName: "John",
        email: "john.smith@gmail.com",
        responsibilities: [
            
                greenID: "8b8a9eb9-840f-4245-9200-719fe05f6612",
                RID: "8e76e90c-8088-40d3-add3-e39c1d4024d8",
                status: "pending"
            
        ]
    

    uuidv4
    .mockReturnValue(null)  // should only be called twice
    .mockReturnValueOnce(johnECResultStoredObject.ECID)  // for ECID
    .mockReturnValueOnce(johnECResultStoredObject.responsibilities[0].RID)  // for RID

    ECs.push(johnECResultStoredObject.ECID);  // to delete the object after the test execution

    try 
        await handler(johnECInitialRequestParams, undefined, undefined);
    
    catch (err) 
        console.error(err);
        throw err
    
    expect(await getUser(johnECResultStoredObject.ECID)).toMatchObject(johnECResultStoredObject);
);

【问题讨论】:

【参考方案1】:

导入后,在您的测试文件中添加 jest.useFakeTimers()

【讨论】:

以上是关于由 AWS SDK 导致的环境被破坏后尝试导入的笑话的主要内容,如果未能解决你的问题,请参考以下文章

使用 aws-sdk 终止实例后删除子网时发生 DependencyViolation

为啥我微信里所有链接打开图片都是空白,显示不了?求大神。

Heroku 在导入“aws-sdk”时崩溃

取消 asyncio 任务导致“任务被破坏但它处于挂起状态”

服务器数据恢复AIX系统环境下PV MAP出错,LV数据被破坏的数据恢复案例

AWS Cloudformation错误:由于递归导入而导致的递归锁定