0

と呼ばれていることを認識していない私は、テストディレクティブに使用するテストコンポーネントを持っている:角度 - ユニットテストのスパイは、機能が

export class UnitTestComponent implements OnInit { 
    @ViewChild(BackgroundLoadedDirective) backgroundLoaded: BackgroundLoadedDirective; 

    public url = 'https://www.codeproject.com/KB/GDI-plus/ImageProcessing2/flip.jpg'; 

    constructor() {} 

    ngOnInit() {} 

    loaded(): void { 
    console.log(true) 
    } 
} 

その後、私は、私はいくつかを書きたいと思い、このディレクティブを持っています以下のためのテスト:問題があるということ

describe('BackgroundLoadedDirective',() => { 

    let component: UnitTestComponent; 
    let fixture: ComponentFixture<UnitTestComponent>; 
    let spy: any; 

    beforeEach(() => { 

    TestBed.configureTestingModule({ 
     declarations: [ 
     UnitTestComponent, 
     BackgroundLoadedDirective 
     ], 
     schemas: [NO_ERRORS_SCHEMA], 
     providers: [ 
     {provide: ComponentFixtureAutoDetect, useValue: true} 
     ] 
    }); 

    fixture = TestBed.createComponent(UnitTestComponent); 
    component = fixture.componentInstance; 
    }); 

    it('should create a fake img tag',() => { 

    spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough(); 

    expect(component.backgroundLoaded.img).toBeTruthy(); 
    expect(spy).toHaveBeenCalled(); 
    }); 
}); 

@Directive({ 
    selector: '[backgroundLoaded]' 
}) 

export class BackgroundLoadedDirective { 
    @Input('backgroundLoaded') set url(value) { 
    this.createImage(value); 
    }; 

    get url() { 
    return this._url; 
    } 

    @Output() loaded: EventEmitter<any> = new EventEmitter<any>(); 

    public img: HTMLImageElement; 

    private _url: string; 

    @HostBinding('class.background-loaded') 
    isLoaded = false; 

    createImage(url: string): void { 

    // This gets logged as expected 
    console.log(url); 

    this._url = url; 

    this.img = new Image(); 

    this.img.onload =() => { 
     this.isLoaded = true; 
     this.load.emit(url); 
    }; 

    this.img.src = url; 
    } 
} 

は、その後、私はこれまでのところだけ、このテストを持っていますテストは次のように失敗します。

機能が呼び出されてもスパイが機能しないのはなぜですか?

EDIT:

ただ、明確に、このディレクティブを適用し、それにURLを与えるテストコンポーネントのhtmlです。

<div [urlToBackground]="url" [backgroundLoaded]="url" (loaded)="loaded($event)"></div> 
+0

は、たぶん私は盲目だけど、私はどこにこの関数を呼び出して表示されません。 – lexith

+0

'.and.callThrough();'が関数を呼び出すと予想されましたか? –

+0

彼は彼のセッター機能のためにそれを呼び出す彼のtestComponentsテンプレートのURLを設定すると思います。これを確認できますか? – lexith

答えて

1

角度のライフサイクルフックは基本的に干渉します。あなたのテストはちょうどタイミングの面で十分ではありません。

テストを簡単にするには、変更をトリガーし、セッターが動作しているかどうかをテストします(あなたが監視している機能を呼び出す)。

このような何か:

it('should create a fake img tag',() => { 
    let spy: jasmine.Spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough(); 

    comp.backgroundLoaded.url = 'foobar'; 
    fixture.detectChanges(); // wait for the change detection to kick in 

    expect(spy).toHaveBeenCalled(); 
}); 

はそれがお役に立てば幸いです。

(編集:それはここでは必要ないですし、とにかくテストの前に呼び出されなければなりませんので、ngOnInitのための1 detectChanges()を削除)

関連する問題