gpt4 book ai didi

Angular 单元测试 Observable/Subject with Karma

转载 作者:行者123 更新时间:2023-12-03 23:18:00 24 4
gpt4 key购买 nike

我正在尝试测试组件中的主题更改,但覆盖范围从未进入订阅功能。

标题栏-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);
}

}

标题栏-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 订阅主题以获取下一个带有去抖动的内容并输出相同的文本。

不知道测试哪里出错了,但是覆盖率从来没有覆盖订阅代码。 Internet 上的示例对我没有帮助。

最佳答案

我遇到了同样的问题,但在此线程中从@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();
}));

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

关于Angular 单元测试 Observable/Subject with Karma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45717134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com