0

I have some class like this

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);
  }
}

I have test one method, but on Subscription i don't even know how to start, this is what I have for now

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();
  });
}); 

Does anyone know how to test unsubscribeSubscriptions

1 Answer 1

1

Use jasmine.createSpyObj() method to create some mocked subscriptions and pass them to the unsubscribeSubscriptions() method. Assert whether the unsubscribe method on these subscriptions is called.

E.g.

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();
    });
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.