[Error] [UnhandledPromiseRejection]

김민섭·2022년 10월 24일
0

error

목록 보기
1/1

jest.js를 이용한 test 코드를 작성하던 중에 Promise 구문을 사용하는 과정에서 아래와 같은 오류가 발생했습니다.

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "[object Object]".]

async 함수를 사용하는데 try~catch block으로 감싸지 않았거나 .catch로 처리하지 않은 reject가 있을 때 발생한다고 되어 있습니다. 따라서 error가 발생하는 원인은 다음과 같습니다.

  1. async 함수를 try~catch 구문으로 error 처리를 하지 않은 경우
  2. 반환되는 promise에서 .catch로 reject 처리를 하지 않은 경우

저의 경우에는 2번에 해당하는 문제였습니다.

에러의 원인이었던 코드

test("should handle errors", async () => {
    const errorMessage = { message: "Error finding product data" };
    const rejectedPromise = Promise.reject(errorMessage);
    productModel.find.mockReturnValue(rejectedPromise);
    await productController.getProducts(req, res, next);
    expect(next).toHaveBeenCalledWith(errorMessage);
  });

.catch로 에러를 해결한 코드

test("should handle errors", async () => {
    const errorMessage = { message: "Error finding product data" };
    const rejectedPromise = Promise.reject(errorMessage).catch((err) => {
      err;
    });
    productModel.find.mockReturnValue(rejectedPromise);
    await productController.getProducts(req, res, next);
    expect(next).toHaveBeenCalledWith(errorMessage);
  });
profile
getting ready to run

0개의 댓글