我正在尝试使用 AngularFire 2 auth 为示例 Angular 2 应用程序设置单元测试,该组件非常简单:
import { Component } from '@angular/core';
import { AngularFire, AuthProviders } from 'angularfire2';
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
isLoggedIn: boolean;
constructor(public af: AngularFire) {
this.af.auth.subscribe(auth => {
if (auth) {
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
});
}
loginWithFacebook() {
this.af.auth.login({
provider: AuthProviders.Facebook
});
}
logout() {
this.af.auth.logout();
}
}
我所做的只是在 AngularFire 中封装login
andlogout
方法,所以我正在考虑使用模拟来检查方法是否被调用,但我不确定从哪里开始,我尝试在我的规范文件中执行以下操作:
import { provide } from '@angular/core';
import { AngularFire } from 'angularfire2';
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
} from '@angular/core/testing';
import { AppComponent } from './app.component';
spyOn(AngularFire, 'auth');
beforeEachProviders(() => [
AppComponent,
AngularFire
]);
describe('App Component', () => {
it('should create the app',
inject([AppComponent], (app: AppComponent) => {
expect(app).toBeTruthy();
})
);
it('should log user in',
inject([AppComponent], (app: AppComponent) => {
expect(app.fb.auth.login).toHaveBeenCalled();
})
);
it('should log user out',
inject([AppComponent], (app: AppComponent) => {
expect(app.fb.auth.logout).toHaveBeenCalled();
})
);
});
但是我不确定如何模拟login
andlogout
方法,因为它们是auth
属性的一部分,有没有办法模拟auth
以及返回login
和logout
方法?