Unit Testing - TestBed - Getting Real Data & Test Request

I’m trying to make a test on the real data back from the API and also for the method type

    describe('AuthService', () => {
      let service: AuthService;
      beforeEach(() => {
         TestBed.configureTestingModule({
          imports: [HttpClientModule],
        });
        service = TestBed.inject(AuthService);
      });
      it('should get the data successfully', (done: DoneFn) => {
        service.getPost(1).subscribe((post: Post) => {
          console.log('data is ', post);
          expect(post.id).toEqual(1);
          done();
        });
      });
    });

when I try to add HttpTestingController & HttpClientTestingModule it gives me an error for that it can’t be resolved in 5000ms
how to test on the real data and test request in the same describe

1 Like

Hello @OmarioHasan,

The beforeEach block is called in every test case (it) inside of the describe scope.

We can’t use HttpClientModule and HttpClientTestingModule at the same time, so we need two Angular test module configurations.

We could do something like this:

describe('AuthService', () => {
  let service: AuthService;

  describe('(with real backend)', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [HttpClientModule],
      });
      service = TestBed.inject(AuthService);
    });
    
    it('should get the data successfully', (done: DoneFn) => {
      service.getPost(1).subscribe((post: Post) => {
          console.log('data is ', post);
          expect(post.id).toEqual(1);
          done();
      });
    });
  });

  describe('(isolated from backend)', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
      });
      service = TestBed.inject(AuthService);
    });
    
    it('should get the data successfully', () => {
      // (...)
    });
  });
});

I recommend this article to learn about HttpClientTestingModule:

1 Like

Thank you it helped me a lot

1 Like