angular - 关闭按钮的 Jasmine 测试用例
问题描述
这是我第一次写测试用例。
我想为隐藏横幅的方法编写测试用例,close
它还会设置一个cookie,这样当用户第二次访问该站点时,它就不会再次出现。
我想涵盖以下场景
close
单击按钮时应调用该方法close
调用方法后应该隐藏 mat-card- 应该已经创建了 Cookie。
请指导我。
下面是我的代码
零件
export class APComponent {
private cookie: any;
private cpBanner: boolean;
constructor(
private cookieService: CookieService) {
this.cookie = this.cookieService.get('CP_BANNER');
this.cpBanner = this.cookie ? false : true;
}
close() {
this.cpBanner = false;
this.cookieService.put( 'CP_BANNER', 'true' );
}
}
HTML
<mat-card *ngIf="apBanner"><mat-card-actions>
<mat-icon name="cross" cropped="cropped" (click)="close()"></mat-icon>
</mat-card-actions></mat-card>
我的规格
describe('APComponent', () => {
let fixture: ComponentFixture<APComponent>;
let component: APComponent;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
declarations: [ APComponent ],
imports: [CommonModule, CookieModule.forRoot()],
});
TestBed.compileComponents();
fixture = TestBed.createComponent(APComponent);
});
it('should create the app', async(() => {
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should close the banner', async(() => {
}));
});
解决方案
这就是您在单元测试方法方面需要涵盖的全部内容。测试在close
单击按钮时调用它更适合于 e2e 测试中的功能测试。
第一个测试检查它是否将实例变量设置为 false。为了确保是这种情况,我们在调用 close() 之前手动将变量设置为 true。
it('should close the banner', async(() => {
// Arrange
const app = fixture.debugElement.componentInstance;
app.cpBanner = true;
// Act
app.close();
// Assert
expect(app.cpBanner).toBe(false);
}));
第二个测试检查它是否调用服务来创建 cookie。毕竟 close 方法实际上并没有创建 cookie。测试 cookie 的实际创建应该在 CookieService 的规范文件中。要断言某个方法已被调用,请使用 Jasmine spies。因此,我们首先获取注入到应用程序的服务的句柄并监视其 put 方法。
注意:我无法验证下面的代码是否有效,因为我没有该服务,但它至少应该演示逻辑。
it('should call the cookie service to create the cookie', async(() => {
// Arrange
const app = fixture.debugElement.componentInstance;
const cookieService = fixture.TestBed.get(CookieService);
spyOn(cookieService, 'put');
// Act
app.close();
// Assert
expect(cookieService.put).toHaveBeenCalledWith('CP_BANNER', 'true');
}));
推荐阅读
- rust - 如何正确地表征与对象不安全类型一起使用的对象?
- sql - 如何在sql中生成从特定星期一到当前日期的星期一日期表
- gtk - 如何设置GtkGrid的行数和列数?
- c - 使用 simd 在双精度数组中查找 nan
- javascript - Anchor 标记的 Java Script 内联函数
- mysql - MySql - 使用哪种列类型在多列中存储多个布尔值?
- codeigniter-4 - 如何在codeigniter 4的视图中访问数据库连接
- math - 使用 Pari 的卡迈克尔数
- java - 将二维 ArrayList 转换为二维数组
- python - scipy.sparse.diags:ValueError:不同数量的对角线和偏移量