javascript - Angular中setTimeOut的单元测试
问题描述
我刚开始学习有关 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(something).toEqual(true)
并且失败消息说expected false to be true
需要时间来找出expect
s 中的哪一个失败时。
PS:setTimeout
是Angular中的一种气味。可能有更好的解决方案。很难从这段简短的代码摘录中说出什么味道。
推荐阅读
- css - 如何激活 :focus on input[type="checkbox"]?
- laravel-backpack - laravel Backpack 中单个 CRUD 页面上的多个 CrudPanel
- visual-studio - 容器仅在从 Visual Studio 运行时有效
- c++ - 在 Azure Pipelines 中安装 Windows SDK 8.1 版本
- android - Espresso UI 测试,无法检查加载状态,如何使用实时数据和视图模型测试 UI?
- python - 使用 Pandas 进行嵌套 JSON 标准化,KeyError:“尝试使用错误运行='ignore',因为键 'company' 并不总是存在”
- python - Python3 - 使用最低权重将模式 A 更改为 B
- python - 在 Python2.6 上为 Windows 安装 quickfix 库的问题
- node.js - 如何对“数组包含”进行反向查询 [firestore]
- url - Vercel 上部署的单个 Nuxt 应用程序上的多个域