使用Karma进行Angular单元测试Observable/Subject

4

我正在尝试测试组件中主题更改,但覆盖范围永远不会进入subscribe函数。

titlebar-search.component.ts

export class TitlebarSearch implements OnInit {

    @ViewChild('titleSearchInput') titleSearchInputEl: any;
    @Input() inputValue: string;
    @Output() searchText = new EventEmitter<string>();
    searchChange: Subject<string> = new Subject<string>();


    constructor(private renderer: Renderer) {

    }    

    /**
     * Waits a time before send the text to search
     * 
     * @protected
     * @memberof TitlebarSearch    
     * 
     */
    protected prepareSearchInput() {
        this.searchChange.debounceTime(500).subscribe(value => {
            this.searchText.emit(value);
        });
    }

    /**
     * Send the text to the searchChange Observable
     * 
     * @param {string} text 
     * @memberof TitlebarSearch
     */
    public doSubmit(text:string){
        this.searchChange.next(text);        
    }    

}

titlebar-search.component.spec.ts

describe('Titlebar Search tests', () => {
    let fixture;
    let titlebarComponent;

    beforeEach(async(() => {
        //Creates a UserService using a mock class
        TestBed.configureTestingModule({
            declarations: [TitlebarSearch],
            imports: [FormsModule],
            //CUSTOM_ELEMENTS_SCHEMA to solve html elements issues
            schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
            providers: [Renderer]
        }).compileComponents().then(() => {
            fixture = TestBed.createComponent(TitlebarSearch);            
            titlebarComponent = fixture.componentInstance
        });

    }));

    //specs
    it('should send the text to detect the change', async((done) => {        
        const text = "Changed text";
        titlebarComponent.doSubmit(text);
        fixture.detectChanges();
        titlebarComponent.searchChange.subscribe(textRecived => {
            expect(textRecived).toEqual(text);
            done();
        })     
    }));           
});

doSubmit方法在输入文本改变时被调用。然后,prepareSearchInput订阅主题以获取下一个内容,使用防抖技术并输出相同的文本。

我不知道测试中出了什么问题,但是代码覆盖率永远不会涵盖订阅代码。互联网上的示例没有帮助到我。

1个回答

5
我曾经遇到过同样的问题,但是在这个线程中从@jonrsharpe那里得到了答案:Unit test Angular 2 service subject
在调用next()之前,你需要在测试中先声明你的主题订阅。如果你按照以下重新排序,应该就可以工作了:
it('should send the text to detect the change', async((done) => {        
    titlebarComponent.searchChange.subscribe(textRecived => {
        expect(textRecived).toEqual(text);
        done();
    })   
    const text = "Changed text";
    titlebarComponent.doSubmit(text);
    fixture.detectChanges();
}));     

据约翰所说,问题在于您的主题没有任何重放/缓冲行为。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接