簡體   English   中英

如何使用笑話在catch塊的if語句中測試函數?

[英]How to test a function within an if statement in catch block using jest?

我有以下代碼:

handler.js

try {
    const body = await calculateSum(event, context);

    return body;
  } catch (err) {

    if (err.response) {
      if (err.response.status === 400) {
        throw new BadRequest('Invalid parameters');
      }

      if (err.response.status === 401 || err.response.status === 403) {
        invokeLambda({
          FunctionName: context.GET_TOKEN,
          InvocationType: 'Event'
        });
      }
    }
    throw new InternalServerError();
  }
}

而且我想用開玩笑的方式對單元調用帶有某些參數的invokeLambda進行單元測試。 有人知道我該怎么做嗎? 我執行了以下操作,但出現錯誤:

handler.test.js

calculateSum.default.mockRejectedValueOnce({
      err: {
        response: {
          status: 401
        }
      }
    });

invokeLambda.mockResolvedValueOnce();
    await handler({
      quantity: 2,
      price: "34.00"
      },
      { GET_TOKEN: 'GET_TOKEN' }
    );

    expect(invokeLambda).toHaveBeenCalledWith({
      FunctionName: 'GET_TOKEN',
      InvocationType: 'Event'
    });

我嘲笑了calculateSum和invokeLambda。我收到錯誤消息TypeError: Cannot read property 'response' of undefined

我相信mockRejectedValueOnce應該通過以下對象

calculateSum.default.mockRejectedValueOnce({
  response: {
    status: 401
  }
});

不需要鍵err因為這是保存錯誤對象的變量的名稱

所以我不得不將我的處理程序調用包裝在一個try catch塊中,如下所示:

calculateTax.default.mockRejectedValueOnce({
    response: {
    status: 401
  }
});

invokeLambda.mockResolvedValueOnce();

try {
  await handler({
      quantity: 2,
      price: "34.00"
      },
      { GET_TOKEN: 'GET_TOKEN' }
    );
} catch (e) {
 // Blah blah
}

expect(invokeLambda).toHaveBeenCalledWith({
      FunctionName: 'GET_TOKEN',
      InvocationType: 'Event'
    });

這是因為我們沒有在if (err.response.status === 401 etc塊中返回任何內容,因此它將一直運行直到到達內部服務錯誤異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM