Angular 2 个组件单元测试

Angular 2 unit test for component

我在 webpack 2 中使用 ng2。

我不知道如何测试组件功能 这是我的组件

import { Component, OnInit } from '@angular/core';
import { GlobalDataService } from '../global.service';
import { Router } from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: './login.component.html'
})
export class LoginComponent {
    constructor(private gd: GlobalDataService, private router: Router) { }
    login(): void {
        this.gd.shareObj['role'] = 'admin';
        this.router.navigateByUrl('/login');
    }
}

我想测试 login() 函数,如果 this.gd.shareObj['role'] = 'admin';确实设置为管理员。

.spec.ts 文件会是什么样子?

我会这样做:

class RouterStub {
  navigateByUrl(url: String) { return url; }
}

class GlobalDataServiceStub {
  shareObj: any = {};
}

describe('LoginComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [LoginComponent],
       providers: [
         { provide: GlobalDataService, useClass: GlobalDataServiceStub },
         { provide: Router, useClass: RouterStub }
       ]
    });

    fixture = TestBed.createComponent(LoginComponent);
    comp = fixture.componentInstance;
  });

  it('should set role to admin',
    inject([GlobalDataService], (gd: GlobalDataService) => {
        comp.login();
        expect(gd.shareObj['role']).toBe('admin');
    })
  );

});

Plunker Example