2017-08-04 9 views
2

私は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を変更することはできません。

しかし、ボタンのクリックをシミュレートして関数をトリガーすると、noUsernamenoPasswordのプロパティが変更されます。

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 

なぜ、どのようにこの問題を解決するために、誰もが私に説明することができます(私は孤立ユニットテストを使用して考えていたが、私はサービスを持っているので、設定は多くの仕事になると思いますか?)

答えて

0

私は最終的にどこに問題があるのか​​把握しました。

私たちが関数をスパイすると、ジャスミンスパイはスパイするためにスパイ関数をスタブします。この場合、関数はその実際の機能を失います。私のコードからspyOn関数を削除すると、それは完全に機能します!

は、機能性と機能の呼び出しをテストするために2つの別々のスペックを使用します。同じ問題に遭遇した人々に

ソース:https://jasmine.github.io/2.0/introduction.html

0

あなたはスパイ-時に機能が正常に呼ばれるようにしたい場合は、お使いのスパイステートメントに.and.callThrough()を追加します。

あなたはspyOn(component, 'setStarFlag').and.callThrough();

component.setStarFlag(true, false);

を呼び出す必要があります
関連する問題