简体   繁体   中英

Mock a component method with spy, karma and jasmine

I have this kind of error during my tests :

ERROR: 'Error during cleanup of component'

I located the origin in :

ngOnDestroy(){
    methodCallToMock()
}

I need to mock methodCallToMock() which is a method of the same component, for it to return false and do nothing else.

My test file :

describe('ChatWindowComponent', () => {
  let component: ChatWindowComponent;
  let fixture: ComponentFixture<ChatWindowComponent>;
  let spy: any;

  const MockMessageService = {
    getMessages: (i: string) => Observable.of([]),
  };

  const MockSocketIoService = {
    onTyping: () => Observable.of({}),
    onStoppedTyping: () => Observable.of({}),
    onNewMessage: () => Observable.of({}),
    onReadConfirmation: () => Observable.of({}),
    onReceptConfirmation: () => Observable.of({}),
  };

  const MockUserService = {
    getCurrentUserFromLocalStorage: () => '',
  };


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [MaterializeModule, FormsModule],
      declarations: [ChatWindowComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [Logger,
        TrackingCommunicationService,
        {provide: SocketioService, useValue: MockSocketIoService},
        {provide: MessageService, useValue: MockMessageService},
        {provide: UserService, useValue: MockUserService}],
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChatWindowComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  afterEach(() => {
    component = null;
  });

  it('should create', () => {
    spy = spyOn(component, 'methodCallToMock').and.returnValue(false);
    expect(component).toBeTruthy();
  });
});

I tried several approach like :

  it('should create', () => {
    spy = spyOn(component, 'methodCallToMock').and.returnValue(false);
    expect(component).toBeTruthy();
  });

But same error, how can I correct this error ?

Found the solution which was really simple...

Just add the method signature to the service mock like that :

  const MockSocketIoService = {
    methodCallToMock() {
    },
    onTyping: () => Observable.of({}),
    onStoppedTyping: () => Observable.of({}),
    onNewMessage: () => Observable.of({}),
    onReadConfirmation: () => Observable.of({}),
    onReceptConfirmation: () => Observable.of({}),
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM