用间谍,业力和茉莉嘲笑一个组件方法

时间:2018-03-07 15:13:34

标签: javascript angular unit-testing typescript karma-jasmine

我在测试期间遇到这种错误:

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

但同样的错误,我该如何纠正这个错误?

1 个答案:

答案 0 :(得分:0)

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

只需将方法签名添加到服务模拟中:

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