![](/img/trans.png)
[英]How to write unit test in angular for setTimeout function and activeElement?
[英]Unit Test for setTimeOut in Angular
我剛剛開始學習有關 Angular 單元測試的新知識。 我已經閱讀了一些文章,但是當我為 setTimeOut 條件實現創建測試用例時,我仍然卡住了。 我在 .component.ts 中有函數
resetDropdown(elementId) {
setTimeout(() => {
if (elementId !== 'free-text-head-'.concat(this.id)) {
if (elementId !== this.id) {
if (this.isFreeTextEnabled && elementId !== 'free-text-body-'.concat(this.id)) {
this.isFreeTextEnabled = false;
this.assignSearchKeywowrd(this.value, this.config.displayKeyMain, this.config.selectedKey);
this.isFreeTextSearchEmpty = false;
this.listData = this.options;
}
}
}
}, 100);
}
我如何在茉莉花中創建這個? 謝謝你們的幫助
fakeAsync
+ tick
對此非常方便。
describe('#resetDropdown when isFreeTextEnabled is true and argument is nor 'free-text-head-'.concat(component.id), nor 'free-text-body-'.concat(component.id), nor component.id', ()=>{
const mockOptions = {someOption: 'someValue'};
beforeEach(() => fakeAsync({
component.options = mockOptions;
component.isFreeTextEnabled = true;
component.id = 'something not similar to argument';
component.resetDropdown('something not similar to component.id');
tick(100);
}))
it(`sets isFreeTextEnabled to false`, () => {
expect(component.isFreeTextEnabled).toEqual(false)
});
it(`sets isFreeTextSearchEmpty to false`, () => {
expect(component.isFreeTextSearchEmpty).toEqual(false)
});
it(`sets component.listData to component.options`, () => {
expect(component.listData).toEqual(mockOptions)
});
});
在it
只保留一個 expect 是一種有用的做法。 當測試失敗時,可以很容易地識別出問題所在。 當有幾行像expect(something).toEqual(true)
並且失敗消息說expected false to be true
,需要時間來找出expect
s 中的哪一個失敗。
PS: setTimeout
是 Angular 中的一種味道。 可能有更好的解決方案。 很難說這段簡短的代碼摘錄有什么味道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.