首页 > 解决方案 > 关闭按钮的 Jasmine 测试用例

问题描述

这是我第一次写测试用例。

我想为隐藏横幅的方法编写测试用例,close它还会设置一个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(() => {

    }));

});

标签: angularjasminekarma-jasmine

解决方案


这就是您在单元测试方法方面需要涵盖的全部内容。测试在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');
}));

推荐阅读