Angular2 - 来自测试组件

时间:2017-01-30 15:29:26

标签: unit-testing angular typescript karma-jasmine

我目前正在和Karma和Jasmine一起为Angular2编写单元测试,但我在单元测试方面很新,而且我遇到了一些困难。当涉及到测试不涉及异步函数的硬编码属性或属性时,它都没关系,但我需要能够调用组件的函数以便某些变量获取它们的值。我正在做的是以下内容:

我的组件:

export class LoginComponent implements OnInit {

formLoginId: string;
loginUrl: string;
email: string;
password: string;

constructor(private googleAuthService: GoogleAuthService,
            private authService: AuthenticationService,
            private validationService: ValidationService,
            private router: Router,
            private titleService: Title) {
    this.titleService.setTitle("Login");
    this.formLoginId = "#form-login";
}

ngOnInit() {

    this.googleAuthService.getLink((response) => {
        this.loginUrl= response.json().url;
    });       
}

login() {
    if (this.validationService.isValid(this.formLoginId)) {
        this.authService.login(this.email, this.password);
    }
}

现在我想编写一个单元测试,它可以检查loginUrl是否取了任何值。我的测试如下:

describe('Login Component', ()=> {
    let component:LoginComponent;
    let fixture:any;

    beforeEach(async(()=> {
        TestBed.configureTestingModule({
            //declarations,imports and providers
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.componentInstance;
    });   /some-other-tests/

    it('should have login url', fakeAsync(()=> {
        component.ngOnInit();
        tick(1000);
        expect(component.loginUrl).toBeDefined();
    }));
});

但它似乎不起作用。对于上面提到的变量,我仍然未定义。如何从组件调用方法并在结果后检查变量?

谢谢!

1 个答案:

答案 0 :(得分:0)

在这种情况下,您需要模拟GoogleAuthService以返回一些信息,否则getLink永远无法解析。

您可以为GoogleAuthService指定模拟提供程序,并让它返回已经解析的可观察对象。