test async function with jest throw and not throw

Viewed 25

I need test async function with jest, but my function have a throw new Error('').
i do this:

await useCase.execute().then(r => {
   expect(r).not.toThrow();
});

but I don't have success because the r is undefined.
I need test if Throw() and I need test if not throw().
I try it:

expect(carryOutTransaction.execute(value, accountOrigin, accountDestination)).rejects.not.toThrow();

but the received is undefined

  const err = new JestAssertionError();
              ^

JestAssertionError: expect(received).rejects.not.toThrow()

Received promise resolved instead of rejected
Resolved to value: undefined

Then I try it:

expect(carryOutTransaction.execute(value, accountOrigin, accountDestination)).not.toThrow();

but I received this error:

    expect(received).not.toThrow()

    Matcher error: received value must be a function

    Received has type:  object
    Received has value: {}

This is my code:

  • async function
    async execute(value: number, accountOriginUUID: string, accountDestinationUUID: string) {
        if(value < 0) {
            throw new Error("Value is not valid");
        }

        const accountOriginDatabase = await this.accountRepository.getAccountById(accountDestinationUUID);
        const accountDestinationDatabase = await this.accountRepository.getAccountById(accountOriginUUID);

        if(accountOriginDatabase == undefined || accountDestinationDatabase == undefined) {
            throw new Error("not find account");
        }

        const accountOrigin = new Account(
            accountOriginDatabase.id, accountOriginDatabase.idClient, accountOriginDatabase.idBank, accountOriginDatabase.money - value
        );
        const accountDestination = new Account(
            accountDestinationDatabase.id, accountDestinationDatabase.idClient, accountDestinationDatabase.idBank, accountDestinationDatabase.money + value
        );

        this.accountRepository.update(accountOrigin);
        this.accountRepository.update(accountDestination);

        const transaction: Transaction = new Transaction('', value, accountDestinationUUID, accountOriginUUID);
        this.transactionRepository.save(transaction);
    }
  • test async function
    test.each(validValues)(
        'should complete the transaction without any problmes if carry out transaction with value $value from $accountOrigin to $accountDestination', 
        async ({value, accountDestination, accountOrigin}) => {
            await carryOutTransaction.execute(value, accountOrigin, accountDestination).then(response => {
                expect(response).not.toThrow();
        });
    });

and this is link code repo: https://github.com/GuilhermeGiacomoSimoes/ka_pay/tree/develop/src/domain/useCases

0 Answers
Related