21

I am testing services with an Http dependency. Every test looks like this :

import { TestBed, async, inject } from '@angular/core/testing';
import { ValidationService } from './validation.service';
import { HttpModule, Http, Response, ResponseOptions, RequestOptions, Headers, XHRBackend } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

describe('DashboardService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        ValidationService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  it('should ...',
    inject([ValidationService, XHRBackend],
      (service: ValidationService, mockBackEnd: MockBackend) => {
        mockBackEnd.connections.subscribe((connection: MockConnection) => {
          connection.mockRespond(new Response(new ResponseOptions({
            body: JSON.stringify('content')
          })));
        });
      }));
      // assertions ...
});

As you can see, I need to inject the BackEnd mock at every it.

Is it possible to use a beforeEach to inject the dependency before every test ?

1 Answer 1

49

Is it possible to use a beforeEach to inject the dependency before every test ?

Sure you could.

let service;

beforeEach(inject([Service], (svc) => {
  service = svc;
}))

Though you could also just get the service from the TestBed, which is also an injector

let service;

beforeEach(() => {
  TestBed.configureTestingModule({
    ...
  })

  service = TestBed.get(Service);
})
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you, I will try both ways to see what fits me best.
is there a way to inject Service without using TestBed setup?
I get the error Error: StaticInjectorError[Service]: NullInjectorError: No provider for Service!
@MonkeySupersonic did you configure it in the TestBed? You still need to do that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.