【发布时间】:2016-10-28 19:36:47
【问题描述】:
我正在尝试使用 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 和 logout 方法,所以我正在考虑使用模拟来检查是否调用了这些方法,但我不确定从哪里开始,我试着做我的规范文件中的以下内容:
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 和 logout 方法,因为它们是 auth 属性的一部分,有没有办法模拟 auth 以及返回的 login 和logout 方法?
【问题讨论】:
-
感兴趣的读者应该关注this issue,以减少这方面的痛苦。
标签: unit-testing angular jasmine karma-jasmine angularfire2