Treatment of negative test cases with JEST

Asked

Viewed 58 times

-1

I have a Code Jest who should test a business rule that says:

No client must have an invalid CPF

it(" should not be able to create a new user whith a wrong CPF",async()=>{

    const repositoryFake = new FakeUserRepository();

    const createUserService = new CreateUserService(repositoryFake);

    expect(await createUserService.execute({
        name:"Joao Geraldo da Cruz",
        password:"321",
        cpf:"50989120003",
    })).rejects.toBeInstanceOf(Error)
})

However, when calling the service, it breaks the code:

public async execute({name, password, cpf}:IUserInterface):Promise<User> {

    if (cpf) {
        if (!DocumentValidation.cpf(cpf)) {
//ele cai nessa validação aqui
            throw new Error("CPF not is valid");
        }
    }

    const user = await this.repository.create({
        name, password, cpf
    });

    return user;
}

The system was actually expected to break down, but Jest should understand this as "normal" and give sucess.

1 answer

0


In your case, if you expect createUserService.execute launch a Error, you should use the await before the expect, That means telling Jest to expect an asynchronous function to be rejected (rejects) and compare the return of this rejection:

await expect(createUserService.execute({
      name:"Joao Geraldo da Cruz",
      password:"321",
      cpf:"50989120003",
  })).rejects.toBeInstanceOf(Error)

Has the documentation of Jest which explains this using async/await.

To the rejects take effect, the function passes to expect has to return a Promise and the way you put it, the await expects the function to return a result instead of having a file for the expect, we have an object Error, soon the rejects will not work because the object of expect is not a Promise.

  • 1

    resolved here Thanks!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.