单元测试订阅 angular 打字稿

Unit test Subscription angular typescript

我有一些class这样的

export class Helper {
  static unsubscribeSubscriptions(subscriptions: Subscription[]): void {
    subscriptions.forEach(subscription => {
      if (subscription) {
        subscription.unsubscribe();
      }
    });
  }

  static isNullOrEmpty(value: string): boolean {
    return (!value || value === undefined || value === '' || value.length === 0);
  }
}

我已经测试了一种方法,但是在订阅上我什至不知道如何开始,这就是我现在所拥有的

describe('Helper', () => {
  it('isNullOrEmpty should return true', () => {
    // WHEN
    const value = '';
    const res = Helper.isNullOrEmpty(value);
    // /THEN
    expect(res).toBeTruthy();
  });

  it('isNullOrEmpty should return true', () => {
     // WHEN
     const value = 'FULL';
     const res = Helper.isNullOrEmpty(value);
     // /THEN
     expect(res).toBeFalsy();
  });
}); 

有谁知道如何测试unsubscribeSubscriptions

使用 jasmine.createSpyObj() 方法创建一些模拟订阅并将它们传递给 unsubscribeSubscriptions() 方法。断言是否调用了这些订阅的取消订阅方法。

例如

helper.ts:

import { Subscription } from 'rxjs';

export class Helper {
  static unsubscribeSubscriptions(subscriptions: Subscription[]): void {
    subscriptions.forEach((subscription) => {
      if (subscription) {
        subscription.unsubscribe();
      }
    });
  }

  static isNullOrEmpty(value: string): boolean {
    return !value || value === undefined || value === '' || value.length === 0;
  }
}

helper.test.ts:

import { Helper } from './helper';

fdescribe('Helper', () => {
  describe('isNullOrEmpty', () => {
    it('should return true', () => {
      const value = '';
      const res = Helper.isNullOrEmpty(value);
      expect(res).toBeTruthy();
    });

    it('should return false', () => {
      const value = 'FULL';
      const res = Helper.isNullOrEmpty(value);
      expect(res).toBeFalsy();
    });
  });

  describe('unsubscribeSubscriptions', () => {
    it('should unsubscribe all subscriptions', () => {
      const sub1 = jasmine.createSpyObj('sub1', ['unsubscribe']);
      const sub2 = jasmine.createSpyObj('sub1', ['unsubscribe']);
      const subscriptions = [sub1, sub2];
      Helper.unsubscribeSubscriptions(subscriptions);
      expect(sub1.unsubscribe).toHaveBeenCalled();
      expect(sub2.unsubscribe).toHaveBeenCalled();
    });
  });
});