Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

SignUp Component não está sendo instanciado

Estou com um problema ao instanciar o SignUpComponent nos teste:

describe("SignUp Component", () => {

    let component: SignupComponent; 
    let signupService: SignUpService; 
    let router: Router; 

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule, VmessageModule, ReactiveFormsModule, RouterTestingModule.withRoutes([])],
            providers: [SignUpService, UserNotTakenValidatorService],
            declarations: [SignupComponent]
        }).compileComponents();
    }));

    beforeEach(() => {
        const fixture = TestBed.createComponent(SignupComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        router = TestBed.get(Router);
        signupService = TestBed.get(SignUpService);
    });

    it("SignUp Component should be instantiated", () => {

        expect(component).toBeTruthy();
    });

    it("must register an user", () => {

        const navigateSpy = spyOn(router, 'navigate');
        spyOn(signupService, 'signup').and.returnValue(of(null));

        component.signupForm.get('email').setValue('alvaro@alvaro.com');
        component.signupForm.get('fullName').setValue('Alvaro');
        component.signupForm.get('userName').setValue('alvaro');
        component.signupForm.get('password').setValue('12345');
        component.signup();
        expect(navigateSpy).toHaveBeenCalledWith(['']);
    });
});

Gerando este erro:

Chrome 89.0.4389.90 (Windows 10) SignUp Component SignUp Component should be instantiated FAILED
        TypeError: Cannot read property 'nativeElement' of undefined
            at SignupComponent.ngOnInit (src/app/home/signup/signup.component.ts:66:77)
            at callHook (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2486:1)
            at callHooks (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2456:1)
            at executeInitAndCheckHooks (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2408:1)
            at refreshView (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9194:1)
            at renderComponentOrTemplate (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9293:1)
            at tickRootContext (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10519:1)
            at detectChangesInRootView (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10544:1)
            at RootViewRef.detectChanges (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22549:1)
            at ComponentFixture._tick (node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:141:1)
2 respostas

O sign-up.component.ts está assim...

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

import { NewUser } from './new-user';
import { SignUpService } from './signup.service';
import { UserNotTakenValidatorService } from './user-not-taken.validator.service';
import { PlatformDetectorService } from 'src/app/core/platform-detector.service';
import { lowerCaseValidator } from 'src/app/shared/validators/lower-case.validator';
import { userNamePassword } from './username.password.validator';

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

    signupForm: FormGroup;
    @ViewChild('inputEmail') inputEmail: 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,
                    lowerCaseValidator,
                    Validators.minLength(2),
                    Validators.maxLength(30)
                ],
                this.userNotTakenValidatorService.checkUserNameTaken()
            ],
            password: ['',
                [
                    Validators.required,
                    Validators.minLength(8),
                    Validators.maxLength(14)
                ]
            ]
        },
        {
            // fazer uma validação que depende de dois campos.
            validator: userNamePassword
        }
        );
        this.platformDetectorService.IsPlatformBrowser() && this.inputEmail.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)
                );
        }
    }
}
solução!

Fala ai Rafael, tudo bem? Reparei que você está utilizando o nativeElement dentro do ngOnInit, o ideal seria utilizá-lo dentro do ngAfterViewInit. 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