【问题标题】:How to spy the element twice to cover the code in karma -jasmine如何监视元素两次以覆盖 karma -jasmine 中的代码
【发布时间】:2021-11-30 00:16:32
【问题描述】:

ts 代码:-

this.shared.refreshPageObeservable().subscribe(data => {
    if (data && Object.keys(data).length) {
        this.userDetails.fullName = `${data.firstName}  ${data.lastName}`;
        this.userDetails.lastLogin = `${data.lastLoginDt}`;
    } else {
        this.userDetails.fullName = '';
        this.userDetails.lastLogin = '';
    }
});

规格文件:-

spyOn(shared, 'refreshPageObeservable').and.returnValue(of({firstName: 'john', lastName: 'doe', lastLoginDt: '12345'}));

fixture.detectChanges();

这段代码覆盖了 if 语句,但是如何覆盖 else 部分。

【问题讨论】:

    标签: jasmine karma-jasmine angular-test


    【解决方案1】:

    给一个空对象,所以 if 语句中的 Object.keys(data).length 为假,所以它转到 else 块

    it('should set fullName and lastLogin to an empty string', () => {
      spyOn(shared, 'refreshPageObeservable').and.returnValue(of({}));
      // call the function again that is responsible for subscribing to that stream
      expect(component.userDetails.fullName).toBe('');
      expect(component.userDetails.lastLogin).toBe('');
    });
    

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 1970-01-01
      • 2016-04-02
      • 2015-06-18
      • 2016-01-12
      • 2014-06-06
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多