jeudi 30 août 2018

Angular - Unit testing Subject()?

I have a Angular service that simply uses a Subject, but I am unsure of how to write unit tests for it.

I saw this thread, but I didn't find it terribly helpful.

I have attempted to mock next() but I am more than a little lost.

message.service.ts

serviceMsg: Subject<IMessage>;

  constructor() {
    this.serviceMsg = new Subject();
  }

  confirm(action: MessageActions) {
    this.serviceMsg.next({result: true, action: action});
  }

IMessage.ts

export interface IMessage {
  result: boolean;
  action: MessageActions;
}

MessageActions.ts

export enum MessageActions {
  STATUS_UPDATE
}

spec.ts

describe('MessageService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MessageService]
    });
    fixture = TestBed.createComponent(MessageService);
    service = fixture.componentInstance;
    httpMock = TestBed.get(HttpTestingController);
  });

  it('should be created', inject([MessageService], (service: MessageService) => {
    expect(service).toBeTruthy();
  }));

  it('should catch what is emitted', () => {
    const nextSpy = spyOn(service, 'next');
    service.confirm(ACTION);
    expect(nextSpy).toHaveBeenCalled();
  });
});

Aucun commentaire:

Enregistrer un commentaire