私はangular2/4アプリケーションの単体テストを作成していました。私は基本的に関数を呼び出す関数ユニットテストを書いて、コンポーネントオブジェクトが変化する属性を期待しています。ここでangular2テスト:コンポーネントオブジェクト自体を直接呼び出すことはできません
は、コードの一部です:
コンポーネント:
export class LoginComponent{
constructor(private loginService: LoginService){};
noUsername: boolean= false;
noPassword: boolean= false;
setStarFlag(id:boolean, pw:boolean){
this.noUsername = id;
this.noPassword = pw;
}
}
ユニットテスト:
var fixture: ComponentFixture<LoginComponent>,
component: LoginComponent,
loginService: LoginService,
loginServiceStub: LoginServiceStub;
describe('LoginComponent',() => {
beforeEach(async(() => {
//set up testing environment
TestBed.configureTestingModule({
declarations: [LoginComponent],
providers: [
{ provide: HttpModule, useValue: true },
{ provide: Http, useValue: true },
{ provide: Router, useValue: true },
]
}).overrideComponent(LoginComponent, {
set: {
//override original service with a stub one
providers: [
{ provide: LoginService, useClass: LoginServiceStub},
{ provide: ActivatedRoute, useValue: { params: Observable.of({resumePath: 'testpath'})} }
]
}
}).compileComponents().then(() => {
fixture = TestBed.createComponent(LoginComponent); //end testbed config & create fixture that provides access to component instance itself
component = fixture.componentInstance; //getting component itself
loginService = fixture.debugElement.injector.get(LoginService);
});
}));
describe('function setStarFlag',()=>{
it('set the flag to the right values',()=>{
spyOn(component, 'setStarFlag');
component.setStarFlag(true, false);
expect(component.noUsername).toBeTruthy(); //this doesnt work
expect(component.noPassword).toBeFalsy(); //this doesnt work
})
});
の問題は、私が直接使用して関数setStarFlag
を呼び出す場合component.setStarFlag(true, false)
、関数setStarFlag
コンポーネント自体のプロパティnoUsername
およびnoPassword
を変更することはできません。
しかし、ボタンのクリックをシミュレートして関数をトリガーすると、noUsername
とnoPassword
のプロパティが変更されます。
HTMLファイル:
<button (click)="setStarFlag(true, false)"></button>
ユニットテスト:
let btn = fixture.debugElement.query(By.css('button'));
btn.triggerEventHandler('click', null);
expect(component.noUsername).toBeTruthy(); //this works
expect(component.noPassword).toBeFalsy(); // this works
なぜ、どのようにこの問題を解決するために、誰もが私に説明することができます(私は孤立ユニットテストを使用して考えていたが、私はサービスを持っているので、設定は多くの仕事になると思いますか?)