IntoTheDeep
IntoTheDeep

Reputation: 4118

Angular 4 testing error

I get error Error: <toHaveBeenCalled> : Expected a spy, but got undefined., and my code seems to be correct. Component:

@Component({
  selector: 'no-content',
  styleUrls: ['./no-content.component.scss'],
  templateUrl: './no-content.component.html',
})
export class NoContentComponent implements OnInit {
  public constructor(public errorService: ErrorHandlerService) {
  }
  public ngOnInit(): void {
    this.errorService.showError(null);
  }
}

Test:

describe(`no-content`, () => {
  let comp: NoContentComponent;
  let fixture: ComponentFixture<NoContentComponent>;
  let errService: ErrorHandlerService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ NoContentComponent ],
      providers: [ErrorHandlerService]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NoContentComponent);
    comp    = fixture.componentInstance;
    errService = TestBed.get(ErrorHandlerService);
    fixture.detectChanges();
  });

  it('should log ngOnInit', () => {
    spyOn(errService, 'showError');
    expect(errService.showError(null)).not.toHaveBeenCalled();
    comp.ngOnInit();
    expect(errService.showError(null)).toHaveBeenCalled();
  });
}

I have tried also variations with define stub service class, but effect was the same. Whatever I do I get same error. I cannot mock that service. Angular version 4

Upvotes: 0

Views: 209

Answers (1)

IntoTheDeep
IntoTheDeep

Reputation: 4118

expect(errService.showError(null)).toHaveBeenCalled(); replaced with expect(errService.showError).toHaveBeenCalledWith(null);

Upvotes: 1

Related Questions