Unit Testing Angular Observables

自作多情 提交于 2019-12-02 02:28:56

I would probably make the mock hold on to the references of the accept and reject functions. Then in the test you can call them to check that they emit the correct boolean value. Something like

class MockConfirmationService {
  accept: Function;
  reject: Function;

  confirm(config: any) {
    this.accept = config.accept;
    this.reject = config.reject;
  }
}

Then in your test just call the accept to test that true is emitted, and call reject to test that false is emitted.

describe('serivce: ModalService', () => {

  let modalService: ModalService;
  let confirmService: MockConfirmationService;

  beforeEach(() => {
    confirmService = new MockConfirmationService();
    TestBed.configureTestingModule({
      providers: [
        ModalService,
        { provide: ConfirmationService, useValue: confirmService }
      ]
    });

    modalService = TestBed.get(ModalService);
  });

  it('should return true when accepted', async(() => {
    modalService.confirmDelete().subscribe(result => {
      expect(result).toBe(true);
      console.log('accepted test complete');
    });
    confirmService.accept();
  }));

  it('should return false when rejected', async(() => {
    modalService.confirmDelete().subscribe(result => {
      expect(result).toBe(false);
      console.log('rejected test complete');
    });
    confirmService.reject();
  }));
});

I've built off of peeskillet's answer. The p-confirmDialog component calls the subscribe of the service, so I had to added requireConfirmationSource, which I found in the PrimeNg source. My mock is as follows:

//
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
//
export class ConfirmationServiceMock {
    public key: string = 'mock1';
    public header: string = 'Delete Confirmation';
    public icon: string = '';
    public message: string = '';
    //  Call Accept to emulate a user accepting
    public accept: Function;
    //  Call Reject to emulate a user rejecting
    public reject: Function;
    private requireConfirmationSource = new Subject<any>();
    requireConfirmation$ = this.requireConfirmationSource.asObservable();
    //
    public confirm(config: any) {
        console.log( 'In confirm service mock...' );
        this.message = config.message;
        this.accept = config.accept;
        this.reject = config.reject;
        console.log( this.message );
        return this;
    }
}
//
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!