用间谍、业力和茉莉花模拟组件方法



我在测试中遇到了这种错误:

ERROR: 'Error during cleanup of component'

我找到了原点:

ngOnDestroy(){
    methodCallToMock()
}

我需要模拟methodCallToMock((,它是同一组件的方法,因为它返回false并且不做任何其他事情。

我的测试文件:

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

我尝试了几种方法,例如:

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

但是同样的错误,我该如何纠正此错误?

找到了非常简单的解决方案...

只需将方法签名添加到服务模拟中,如下所示:

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

最新更新