4
respostas

Testes não estão passando

Boa tarde!

Os dois últimos testes do SignUpComponent não estão passando.

Os avisos no Karma são esses:

O formulário SignUp > Deve cadastrar um usuário

Expected spy navigate to have been called with: [ [ '' ] ] but it was never called.

e

O formulário SignUp > Deve realizar o log caso ocorra algum erro

Expected spy log to have been called with: [ 'Erro de Servidor' ] but it was never called.

O código fonte está aqui:

describe('O formulário SignUp', () => {
    let component: SignUpComponent
    let router: Router
    let signupService: SignUpService

    beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
            declarations: [SignUpComponent],
            imports: [
                HttpClientTestingModule,
                VMessageModule,
                ReactiveFormsModule,
                RouterTestingModule.withRoutes([])
            ],
            providers: [
                SignUpService,
                UserNotTakenValidatorService
            ]
        }).compileComponents()
    }))

    beforeEach(() => {
        router = TestBed.inject(Router)
        signupService = TestBed.inject(SignUpService)

        const fixture = TestBed.createComponent(SignUpComponent)
        component = fixture.componentInstance
        fixture.detectChanges()
    })

    it('Deve ser instanciado', () => {
        expect(component).toBeTruthy()
    })

    it('Deve cadastrar um usuário', () => {
        const navigateSpy = spyOn(router, 'navigate')
        spyOn(signupService, 'signup').and.returnValue(of(null))

        component.signupForm.get('email').setValue('henrique@mail.com')
        component.signupForm.get('fullName').setValue('Henrique Santos')
        component.signupForm.get('userName').setValue('Henrique')
        component.signupForm.get('password').setValue('123')

        component.signup()

        expect(navigateSpy).toHaveBeenCalledWith([''])
    })

    it('Deve realizar o log caso ocorra algum erro', () => {
        spyOn(signupService, 'signup').and
            .returnValue(throwError('Erro de Servidor'))

        component.signupForm.get('email').setValue('henrique@mail.com')
        component.signupForm.get('fullName').setValue('Henrique Santos')
        component.signupForm.get('userName').setValue('Henrique')
        component.signupForm.get('password').setValue('123')

        const spyLog = spyOn(console, 'log')

        component.signup()

        expect(spyLog).toHaveBeenCalledWith('Erro de Servidor')
    })
})

Alguma ideia de como resolver ?

4 respostas

O código fonte do arquivo signup.component.ts é esse, talvez ajude na resolução...

@Component({
    templateUrl: './signup.component.html',
    providers: [UserNotTakenValidatorService]
})
export class SignUpComponent implements OnInit {

    signupForm: FormGroup
    @ViewChild('emailInput', { static: true }) emailInput: ElementRef<HTMLInputElement>

    constructor(
        private formBuilder: FormBuilder,
        private userNotTakenValidatorService: UserNotTakenValidatorService,
        private signUpService: SignUpService,
        private router: Router,
        private platformDetectorService: PlatformDetectorService
    ) { }

    ngOnInit(): void {
        this.signupForm = this.formBuilder.group({
            email: ['',
                [
                    Validators.required,
                    Validators.email
                ]
            ],
            fullName: ['', 
                [
                    Validators.required,
                    Validators.minLength(2),
                    Validators.maxLength(40)
                ]
            ],
            userName: ['', 
                [
                    Validators.required,
                    Validators.minLength(2),
                    Validators.maxLength(30),
                    lowerCaseValidator
                ],
                this.userNotTakenValidatorService.checkUserNameTaken()
            ],         
            password: ['', 
                [
                    Validators.required,
                    Validators.minLength(8),
                    Validators.maxLength(14),
                ]
            ]
        }, {
            validator: userNamePassword
        })

        this.platformDetectorService.isPlatformBrowser() &&
            this.emailInput.nativeElement.focus();
    }

    signup() {
        if(this.signupForm.valid && !this.signupForm.pending) {
            const newUser = this.signupForm.getRawValue() as NewUser
            this.signUpService
                .signup(newUser)
                .subscribe(
                    () => this.router.navigate(['']),
                    err => console.log(err)
                )
        }
    }
}

Fala ai Henrique, tudo bem? Posso te pedir um favor? Compartilha comigo o projeto completo de como está agora.

Assim eu consigo simular o problema por aqui e analisá-lo com mais calma.

Pode compartilhar através do Github ou Google Drive (zipado).

Fico no aguardo.

Boa noite Matheus! Tudo certo, graças a Deus!

Tá na mão: https://github.com/Henrique-Santos/Angular

Fala ai Henrique, tudo bem? Dei uma olhada no seu projeto, o problema é que os valores do seu formulário estavam inválidos, dessa forma, ele não entrava dentro dessa condição: if(this.signupForm.valid && !this.signupForm.pending)

Isso porque no teste você informou a senha muito pequena e o nome de usuário com maiuscula:

component.signupForm.get('userName').setValue('Henrique')
component.signupForm.get('password').setValue('123')

Mude para (em ambos os testes):

component.signupForm.get('userName').setValue('henrique')
component.signupForm.get('password').setValue('12345678')

Espero ter ajudado.

Espero ter ajudado.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software