Mock provider in Angular2

2019-09-13 05:11发布

问题:

I want to unit test my Angular2 component. As I have other dependencies registered I want to mock some of them, especially which makes server requests.

I have bootsrapped my site using Angular CLI so have auto-generated test wrappers when new component is creating

So my beforeEach is:

  beforeEach(async(() => {
    mockHttpService.get = jasmine.createSpy('mockHttpService.get').and.callFake(() => {return { subscribe: () => {} }});

    TestBed.configureTestingModule({
      declarations: [ MyComponent ],

      //service substitution
      providers: [{provide: Http, useValue: mockHttpService}, ...],
      imports: [HttpModule]
    })
    .compileComponents();
  }));

I've created mock for HTTP service:

let mockHttpService = {get: () => {return { subscribe: () => {} }}};

All I need - it's to check if request was initiated on OnInit stage. So I have very simple test:

  it('should load dictionary data', () => {
    spyOn(mockHttpService, 'get');

    component.ngOnInit();
    expect(mockHttpService.get).toHaveBeenCalled(); //NEVER CALLED
  });

I've cleared all my component logic and have single line in my OnInit handler:

ngOnInit() {
    this.http.get(url).subscribe(result => this.data = result.json());
  }

Why my test says that mockHttpService.get never called?