Programing

Jest에서 throw 된 예외 유형을 테스트하는 방법

lottogame 2020. 11. 7. 08:53
반응형

Jest에서 throw 된 예외 유형을 테스트하는 방법


함수에 의해 throw되는 예외 유형을 테스트해야하는 일부 코드로 작업하고 있습니다 (TypeError, ReferenceError 등).

현재 테스트 프레임 워크는 AVA이며 다음과 같이 두 번째 인수 t.throws방법 으로 테스트 할 수 있습니다.

it('should throw Error with message \'UNKNOWN ERROR\' when no params were passed', (t) => {
  const error = t.throws(() => {
    throwError();
  }, TypeError);

  t.is(error.message, 'UNKNOWN ERROR');
});

Jest에 테스트를 다시 작성하기 시작했지만 쉽게 수행하는 방법을 찾을 수 없었습니다. 가능할까요?


Jest에서는 expect (function) .toThrow (blank 또는 type of error)에 함수를 전달해야합니다.

예:

test("Test description", () => {
  const t = () => {
    throw new TypeError();
  };
  expect(t).toThrow(TypeError);
});

인수 집합과 함께 throw되는지 여부를 기존 함수를 테스트해야하는 경우 expect ()의 익명 함수 안에 래핑해야합니다.

예:

test("Test description", () => {
  expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);
});

조금 이상하지만 작동하고 imho는 읽기 쉽습니다.

it('should throw Error with message \'UNKNOWN ERROR\' when no params were passed', () => {
  try {
      throwError();
      // Fail test if above expression doesn't throw anything.
      expect(true).toBe(false);
  } catch (e) {
      expect(e.message).toBe("UNKNOWN ERROR");
  }
});

Catch블록이 예외를 포착하면 발생한 Error. expect(true).toBe(false);예상하지 못한 경우 테스트에 실패하려면 이상한 것이 필요합니다 Error. 그렇지 않으면이 행에 도달 할 수 없습니다 ( Error앞에 올려야 함).

편집 : @Kenny Body는 사용하는 경우 코드 품질을 향상시키는 더 나은 솔루션을 제안합니다. expect.assertions()

it('should throw Error with message \'UNKNOWN ERROR\' when no params were passed', () => {
  expect.assertions(1);
  try {
      throwError();
  } catch (e) {
      expect(e.message).toBe("UNKNOWN ERROR");
  }
});

자세한 설명과 함께 원래 답변 참조 : Jest에서 throw 된 예외 유형을 테스트하는 방법


약간 더 간결한 버전을 사용합니다.

expect(() => {
  //code block that should throw error
}).toThrow(TypeError) //or .toThrow('expectedErrorMessage')

직접 시도하지는 않았지만 Jest의 toThrow 주장을 사용하는 것이 좋습니다 . 따라서 귀하의 예는 다음과 같이 보일 것입니다.

it('should throw Error with message \'UNKNOWN ERROR\' when no params were passed', (t) => {
  const error = t.throws(() => {
    throwError();
  }, TypeError);

  expect(t).toThrowError('UNKNOWN ERROR');
  //or
  expect(t).toThrowError(TypeError);
});

다시 말하지만, 테스트하지는 않았지만 작동해야한다고 생각합니다.

이것이 도움이되었는지 알려주세요.

즐거운 코딩 되세요!


Jest에는 toThrow(error)함수가 호출 될 때 발생하는지 테스트 하는 메서드 가 있습니다.

So, in your case you should call it so:

expect(t).toThrowError(TypeError);

The docs


From my (albeit limited) exposure to Jest, I have found that expect().toThrow() is suitable if you want to ONLY test an error is thrown with a specific message:

expect(() => functionUnderTest()).toThrow(TypeError);

OR an error is thrown of a specific type:

expect(() => functionUnderTest()).toThrow('Something bad happened!');

If you try to do both, you will get a false positive. For example if your code throws RangeError('Something bad happened!'), this test will pass:

expect(() => functionUnderTest()).toThrow(new TypeError('Something bad happened!'));

The answer by bodolsog which suggests using a try/catch is close, but rather than expecting true to be false to ensure the expect assertions in the catch are hit, you can instead use expect.assertions(2) at the start of your test where 2 is the number of expected assertions. I feel this more accurately describes the intention of the test.

Full example of testing the type AND message of an error:

describe('functionUnderTest', () => {
    it('should throw a specific type of error.', () => {
        expect.assertions(2);

        try {
            functionUnderTest();
        } catch (error) {
            expect(error).toBeInstanceOf(TypeError);
            expect(error).toHaveProperty('message', 'Something bad happened!');
        }
    }); 
});

If functionUnderTest() does NOT throw an error, the assertions will be be hit but the expect.assertions(2) will fail and the test will fail.


try
expect(t).rejects.toThrow()


I ended up writing a convenience method for our test-utils library

/**
 *  Utility method to test for a specific error class and message in Jest
 * @param {fn, expectedErrorClass, expectedErrorMessage }
 * @example   failTest({
      fn: () => {
        return new MyObject({
          param: 'stuff'
        })
      },
      expectedErrorClass: MyError,
      expectedErrorMessage: 'stuff not yet implemented'
    })
 */
  failTest: ({ fn, expectedErrorClass, expectedErrorMessage }) => {
    try {
      fn()
      expect(true).toBeFalsy()
    } catch (err) {
      let isExpectedErr = err instanceof expectedErrorClass
      expect(isExpectedErr).toBeTruthy()
      expect(err.message).toBe(expectedErrorMessage)
    }
  }

참고URL : https://stackoverflow.com/questions/46042613/how-to-test-type-of-thrown-exception-in-jest

반응형