Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Angular2 service testing : inject a dependency with beforeEach

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 ?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
})
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!