如何为 Angular2 的登录组件编写测试(单元测试)

问题描述 投票:0回答:1

这是login.component.ts

    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { CommonModule } from  '@angular/common';

    import { LoginUser } from './loginUser.model'
    import { UserService } from './user.service';
    import { LoaderService } from '../shared/loader.service';

    import 'rxjs/add/operator/toPromise';

    @Component({
        templateUrl: './login.component.html'
    })
    export class LoginComponent implements OnInit {
        errorMessage: string;
        loginForm: FormGroup;
        loginObj = new LoginUser();

        constructor(private userService: UserService, private loaderService: LoaderService, private router: Router, fb: FormBuilder) {
            this.loginForm = fb.group({
                userName: [null, Validators.required],
                password: [null, Validators.required]
            })
            console.log(this.loginForm);
        }

    test() : void{
        console.log("This is a test");
    }
        login(loginObjValue: any): void {
            if (loginObjValue.userName == null || loginObjValue.password == null) {
                console.log('error');
            } else {
                this.loginObj.userName = loginObjValue.userName;
                this.loginObj.password = loginObjValue.password;
                this.loaderService.displayLoader(true);

                this.userService.login(this.loginObj)
                    .then((res) => {
                        console.log("data", res);
                        console.log("$localStorage.currentUser", localStorage);
                        let link = ['customercare/customer-ticket'];
                        this.loaderService.displayLoader(false);

                        this.router.navigate(link);
                    })
                    .catch(error => this.handleError(error));
            }
        }

        private handleError(error: any): Promise<any> {
            this.loaderService.displayLoader(false);

            if (error._body) {
                this.errorMessage = JSON.parse(error._body).error_description;
            }

            console.log('An error occurred', error);
            return Promise.reject(error.message || error);
        }

        ngOnInit(): void {

        }
    }

   
    @Component({
        templateUrl: './login.component.html'
    })
    export class LoginComponent implements OnInit {
        errorMessage: string;
        loginForm: FormGroup;
        loginObj = new LoginUser();
    
        constructor(private userService: UserService, private loaderService: LoaderService, private router: Router, fb: FormBuilder) {
            this.loginForm = fb.group({
                userName: [null, Validators.required],
                password: [null, Validators.required]
            })
            console.log(this.loginForm);
        }
    
   
        login(loginObjValue: any): void {
            if (loginObjValue.userName == null || loginObjValue.password == null) {
                console.log('error');
            } else {
                this.loginObj.userName = loginObjValue.userName;
                this.loginObj.password = loginObjValue.password;
                this.loaderService.displayLoader(true);
    
                this.userService.login(this.loginObj)
                    .then((res) => {
                        console.log("data", res);
                        console.log("$localStorage.currentUser", localStorage);
                        let link = ['customercare/customer-ticket'];
                        this.loaderService.displayLoader(false);
    
                        this.router.navigate(link);
                    })
                    .catch(error => this.handleError(error));
            }
        }
    }

userservice.ts的部分代码

@Injectable()
export class UserService {
    private URL = "";

    constructor(private http: Http) { }

    login(loginObj: LoginUser) {

        let body = 'userName=' + loginObj.userName + '&password=' + loginObj.password + '&grant_type=password';

        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this.http.post(this.URL + '/token', body, { headers: headers })
            .toPromise()
            .then((res: Response) => {
                let data = res.json();
                if (data && data.access_token) {
                    localStorage.setItem('currentUser', JSON.stringify(data));
                }
                return data;
            })
    }
}

到目前为止我已经写了:我无法调用登录功能。

    describe('LoginComponent', () => {
      let component: LoginComponent;
      let UserService:UserService;
      let fixture: ComponentFixture<LoginComponent>;
      
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [ LoginComponent ],
        providers: [
            { provide: UserService, useValue: UserService },
                   ]
      })
 
      it('should call the login method from the UserService', 
        inject([TestBed, UserService], fakeAsync((tcb: TestBed, mockUserService: UserService) => {
          spyOn(mockUserService, 'login');
    tcb
            .createComponent(LoginComponent)
            .then((fixture: ComponentFixture<LoginComponent>) => {
              tick();
               fixture.detectChanges();
              expect(mockUserService.login).toHaveBeenCalled();
            });
        }))
      );
    });
angular jasmine karma-jasmine
1个回答
0
投票

所以我不确定错误是什么,但我看到的最重要的事情可能是在创建组件之前没有调用compileComponents。

beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [ LoginComponent ],
        providers: [
            { provide: UserService, useValue: UserService },
                   ]
      }).compileComponents();
}); <--- also looked to be missing

这只是我的建议,我不在机器附近测试你的方法是否可行,但我也会在每个之前获取对固定装置的引用,并使用它在测试中创建你的组件。与上面相同,但是:

beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [ LoginComponent ],
        providers: [
            { provide: UserService, useValue: UserService },
                   ]
      }).compileComponents();
}); 

beforeEach(async(() => {
      // components are now compiled
      fixture = TestBed.createComponent(LoginComponent);
}); 

主要是在您创建对它的引用之前。您尝试在测试中重新创建该引用,但您可以在 beforeEach 中分配给它并使用它。

此外,您的测试实际上并没有执行任何我认为触发了任何调用的操作。如果这是您的目标,您可以验证它是否存在。

 it('should call the login method when the component does something', 
        inject([UserService], ((userService: UserService) => {
          spyOn(userService, 'login');
          let component = fixture.componentInstance;
          component.doSomething();
          expect(userService.login).toHaveBeenCalled();
          });
 }));

由于您只是测试函数是否被调用,因此实际上不需要将任何内容包装在异步中。您不需要等待 DOM 或其他任何内容中的响应,只需验证在调用组件自己的 login() 方法时确实调用了服务上的 login() 方法。如果有疑问,您可以扔进一个无害的fixture.detectChanges(),但我相信即使这样通常也是为了确保如果您更改了模板中的某些内容,元素已经传播回来。

老实说,即使这也超出了纯粹的单元测试。您可以为 UserService 编写其他单元测试。如果您想验证 LoginComponent 的某些方面,我会编写测试来断言 LoginComponent 登录后应该发生变化或存在的任何内容。(也许 DOM 中的文本已更改,等等)。或者,如果您只是测试业务逻辑,则可以拦截登录调用以返回 true 或 false 并验证 doSomething() 是否做出适当反应。

© www.soinside.com 2019 - 2024. All rights reserved.