Angular testing with json server mock

Viewed 699

i'm new with angular testing and i'm trying to test if mocked json is equal to json in db.json. The problem is that the tests have succes even if json server is down. Here my spec:

import { TestBed } from '@angular/core/testing';
import { ProfileService } from './profile.service';
import { HttpClientTestingModule,
         HttpTestingController } from '@angular/common/http/testing';

describe('ProfileService', () => {
  // We declare the variables that we'll use for the Test Controller and for our Service
  let httpTestingController: HttpTestingController;
  let service: ProfileService;
  
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ProfileService],
      imports: [HttpClientTestingModule]
    });

    // We inject our service (which imports the HttpClient) and the Test Controller
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(ProfileService);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  describe('#getInfoContratto', () => {
    let expectedInfo = JSON.parse('{"abi": "string","banca": "string", "cab": "string","cin": "string","codiceRID": "string","conto": "string", "dataAllineamento": "string","dataAttivazione": "string","dataUltimaModifica": "string","iban": "string","intestatarioConto": "string","nome": "string","societa": "string","sportello": "string","stato": "string","statoAllineamento": "string","tipoGaranzia": "string","valoreDellaFidejussione": "string"}');

    it('should return expected info', () => {
      
      service.getInfoContratto("TEST").subscribe(
      infoContratti => expect(infoContratti).toEqual(expectedInfo, 'should return expected info'),
        fail
      );

      const req = httpTestingController.expectOne({ method: 'POST', url: service.serverUrl+ "accesso-utenti-infoContratto" });
      // expect(req.request.method).toEqual('POST');

      req.flush(expectedInfo);
      console.log(req.request.url);
    });
    
  });

What i'm doing wrong?

1 Answers

Ok, I wanted to post a comment on this but I think the comment would itself be an answer.

The reason your test is passing even when the JSON Server is down is because of HttpClientTestingModule.

What's happening is that your actual (which happens when our app is served) http calls are never happening. They are replaced with mock calls which are done behind the scene by our HttpClientTestingModule.

Question: Why is this happening?

Answer: The essence of unit testing is that you isolate service or component and then test them using dummy data. Hence, the real http calls should always be avoided and should be mocked with some controlled data.

Since you are new to unit testing, I would recommend you to read this article and refer attached article on the same page.

Related