it-source

던질 것으로 예상되는 비동기 테스트를 작성할 수 있습니까?

criticalcode 2022. 11. 29. 21:41
반응형

던질 것으로 예상되는 비동기 테스트를 작성할 수 있습니까?

비동기 함수가 다음과 같이 느려질 것으로 예상하는 비동기 테스트를 쓰고 있습니다.

it("expects to have failed", async () => {
  let getBadResults = async () => {
    await failingAsyncTest()
  }
  expect(await getBadResults()).toThrow()
})

하지만 농담은 시험에 합격하는 것이 아니라 그저 불합격일 뿐이다.

 FAIL  src/failing-test.spec.js
  ● expects to have failed

    Failed: I should fail!

테스트를 다음과 같이 다시 작성하면 다음과 같습니다.

expect(async () => {
  await failingAsyncTest()
}).toThrow()

테스트에 합격하는 대신 다음 오류가 발생합니다.

expect(function).toThrow(undefined)

Expected the function to throw an error.
But it didn't throw anything.

비동기 기능은 다음과 같이 테스트할 수 있습니다.

it('should test async errors', async () =>  {        
    await expect(failingAsyncTest())
    .rejects
    .toThrow('I should fail');
});

I should fail' 문자열은 던져진 오류의 모든 부분과 일치합니다.

여기에 덧붙여, 테스트하는 함수는 실제 에러 오브젝트를 슬로우 할 필요가 있습니다.throw new Error(...)Jeast는 당신이 단지 다음과 같은 표현을 던지면 알아채지 못하는 것 같다.throw 'An error occurred!'.

await expect(async () => { 
    await someAsyncFunction(someParams); 
}).rejects.toThrowError("Some error message");

오류를 포착하기 위해 코드를 함수로 묶어야 합니다.여기서는 someAsyncFunction에서 던져진 오류 메시지가 "Some error message"와 같아야 합니다.예외 핸들러를 호출할 수도 있습니다.

await expect(async () => { 
    await someAsyncFunction(someParams); 
}).rejects.toThrowError(new InvalidArgumentError("Some error message"));

자세한 내용은 https://jestjs.io/docs/expect#tothrowerror를 참조해 주세요.

커스텀 에러 클래스

의 사용rejects.toThrow효과가 없습니다.대신, 이 명령어를 조합하여rejects를 사용한 메서드toBeInstanceOf발생한 커스텀에러에 일치시키는 matcher.

it("should test async errors", async () => {
  await expect(asyncFunctionWithCustomError()).rejects.toBeInstanceOf(
    CustomError
  )
})

매번 약속을 해결하지 않고 많은 테스트 조건을 만들 수 있도록 하기 위해서도 이 방법은 유효합니다.

it('throws an error when it is not possible to create an user', async () => {
        const throwingFunction = () => createUser(createUserPayload)

        // This is what prevents the test to succeed when the promise is resolved and not rejected
        expect.assertions(3)

        await throwingFunction().catch(error => {
            expect(error).toBeInstanceOf(Error)
            expect(error.message).toMatch(new RegExp('Could not create user'))
            expect(error).toMatchObject({
                details: new RegExp('Invalid payload provided'),
            })
        })
    })

Firebase 클라우드 기능을 테스트해 본 결과, 다음과 같은 결과가 나왔습니다.

test("It should test async on failing cloud functions calls", async () => {
    await expect(async ()=> {
        await failingCloudFunction(params)
    })
    .rejects
    .toThrow("Invalid type"); // This is the value for my specific error
  });

이것은 리산드로의 대답 위에 만들어졌다.

이건 내게 효과가 있었다.

it("expects to have failed", async () => {
  let getBadResults = async () => {
    await failingAsyncTest()
  }
  expect(getBadResults()).reject.toMatch('foo')
  // or in my case
  expect(getBadResults()).reject.toMatchObject({ message: 'foo' })
})

test("It should test async on failing cloud functions calls", async () => {
   failingCloudFunction(params).catch(e => {
    expect(e.message).toBe('Invalid type')
   })
  });

언급URL : https://stackoverflow.com/questions/47144187/can-you-write-async-tests-that-expect-tothrow

반응형