Angular 4测试错误

时间:2017-11-02 13:01:58

标签: javascript angular testing karma-jasmine

我收到错误错误:<toHaveBeenCalled> : Expected a spy, but got undefined.,我的代码似乎是正确的。 成分:

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

测试:

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

我也试过定义存根服务类的变体,但效果是一样的。无论我做什么,我都会得到同样的错误。我无法嘲笑那项服务。 Angular版本4

1 个答案:

答案 0 :(得分:1)

expect(errService.showError(null)).toHaveBeenCalled();已替换为expect(errService.showError).toHaveBeenCalledWith(null);