angular - 如何模拟延迟?
问题描述
有包含状态的服务:
@Injectable({
providedIn: 'root'
})
export class WordsService {
words: string[] = [
'qqq',
'www',
'eee',
'rrr',
'ttt',
'yyy',
];
constructor() { }
}
组件中有一个按钮。当用户单击此按钮时,服务状态将显示在模板中。
@Component({
selector: 'app-page3',
template: `
<div *ngFor="let word of serviceWords" class="word-el">
{{ word }}
</div>
<button (click)="getWordsFromService()" id="getWordsBtn">get words from service</button>
`,
styleUrls: ['./page3.component.scss']
})
export class Page3Component {
serviceWords: string[] = [];
constructor(private wordsService: WordsService) { }
getWordsFromService() {
this.serviceWords = this.wordsService.words;
}
}
我尝试模拟延迟,然后检查在模板中显示服务状态。
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ Page3Component ]
})
.compileComponents();
});
it('should display list after getWords-button', () => {
fixture.detectChanges();
const compliedComponent = fixture.debugElement.nativeElement;
const btn = compliedComponent.querySelector('#getWordsBtn');
btn.dispatchEvent(new Event('click'));
setTimeout(() => {
expect(compliedComponent.querySelector('.word-el')).toBeTruthy();
}, 1000);
});
不幸的是,这个单元测试不起作用。我收到以下消息:规范没有期望
请帮我模拟按钮单击后的延迟。
我尝试使用tick()
,waits()
但他们没有工作。
解决方案
- 在这种情况下,您应该
done
在测试中使用 -arg,例如:
it('should display list after getWords-button', (done: DoneFn) => {
fixture.detectChanges();
const compliedComponent = fixture.debugElement.nativeElement;
const btn = compliedComponent.querySelector('#getWordsBtn');
btn.dispatchEvent(new Event('click'));
setTimeout(() => {
expect(compliedComponent.querySelector('.word-el')).toBeTruthy();
done();
}, 1000);
});
- 我认为更改检查的正确方法是检测夹具更改:
it('should display list after getWords-button', () => {
fixture.detectChanges();
const compliedComponent = fixture.debugElement.nativeElement;
const btn = compliedComponent.querySelector('#getWordsBtn');
btn.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(compliedComponent.querySelector('.word-el')).toBeTruthy();
});
推荐阅读
- javascript - 如何将某个计算的 jQuery 结果显示为“不可用”而不是显示 £0
- gitlab - 在 PuTTY 中删除多个克隆的 git 存储库
- python - Python 语法:在行尾时冒号可以是可选的吗?
- html - 嵌套 SVG 会导致意外调整大小
- windows - 执行 npm install react-native-gesture-handler 时出错
- python - 大熊猫中的 GroupBy 并从值创建新列
- r - ggplot R中叠加散点图中的色点
- python - 在基本操作系统(或 Ubuntu)上使用 python 3.8 而不是 3.6
- python - 在 django rest framework 和 postgres 中做太多的写操作
- javascript - 如何将焦点设置在第一个输入或使用类名选择?