【问题标题】:Jasmine Test case for close button关闭按钮的 Jasmine 测试用例
【发布时间】:2018-09-06 18:32:42
【问题描述】:

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

我想为 close 方法编写测试用例,该方法将隐藏横幅并设置一个 cookie,这样当用户第二次访问该网站时,它就不会再次出现。

我想涵盖以下场景

  • 点击按钮时应该调用close方法
  • mat-card 在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(() => {

    }));

});

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    这是您在单元测试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');
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2016-02-12
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多