2017-04-26 66 views
1

我們只想在少數組件上測試ChangeDetection值,但我們沒有找到輕鬆訪問組件元數據的方法。 對於管我們發現:測試組件元數據

it('should be marked as pure',() => { 
     expect(new PipeResolver().resolve(TranslatePipe).pure).toEqual(true); 
    }); 

這裏的主要問題是找到一種簡單的方法來做到這一點的組件和檢查它是否是OnPush與否。這裏有什麼想法? 非常感謝。

+0

'進口{} PipeResolver從 '@角/編譯器';'? – yurzui

回答

3

好像你正在尋找:

new DirectiveResolver().resolve(TestComponent) as Component).changeDetection 

全碼:

import { Component, Pipe, ChangeDetectionStrategy } from '@angular/core'; 
import { PipeResolver, DirectiveResolver } from '@angular/compiler'; 

@Component({ 
    selector: 'app-banner', 
    template: '<h1>{{title}}</h1>', 
    changeDetection: ChangeDetectionStrategy.OnPush 
}) 
export class TestComponent { 
    title = 'Test Tour of Heroes'; 
} 

@Pipe({ 
    name: 'translate', 
    pure: true 
}) 
export class TranslatePipe { 
    transform() { 

    } 
} 


describe('BannerComponent',() => { 
    it('should be marked as pure',() => { 
    expect(new PipeResolver().resolve(TranslatePipe).pure).toEqual(true); 
    }); 

    it('should be marked as onPush',() => { 
    expect((new DirectiveResolver().resolve(TestComponent) as Component).changeDetection).toEqual(ChangeDetectionStrategy.OnPush); 
    }); 
}); 

Plunker Example

+0

這很有趣,你認爲元數據應該被測試嗎? –

+0

DirectiveResolver和PipeResolver是編譯器API的一部分,不知道它是公開的 –

+0

@Maximus我非常肯定它取決於口味 – yurzui