Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Need to call TestBed.initTestEnvironment() first

I'm trying do a test in angular of a service.

This is my part of the code



describe('AddressService', () => {

  let service: AddressService;
  let injector: TestBed;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [AddressService]
    });


    injector = getTestBed();
    service = injector.inject(AddressService);
    httpTestingController = injector.inject(HttpTestingController);
    
    // service = TestBed.inject(AddressService);
    

  });

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

  httpTestingController = TestBed.inject(HttpTestingController);

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  const dummyAddressListResponse = {
    data: [
      {direccion: 'address1'}, {Colas: 'queue1'},
      {direccion: 'address2'}, {Colas: 'queue2'}
    ],
  };

  it('getAddress() should return data', () => {
    service.getAddress().subscribe((res) => {
      expect(res).toEqual(dummyAddressListResponse);
    });

    const req = httpTestingController.expectOne(`${environment.URI}/mock-address`);
    expect(req.request.method).toBe('GET');
    req.flush(dummyAddressListResponse);
  })

});

At the moment of run the test ng test --main src/app/services/address/address.service.spec.ts

I'm seeing this error Error: Need to call TestBed.initTestEnvironment() first

I have searched and don't see any solution, Has it happened to someone?

like image 365
Jesus Burneo Gutierrez Avatar asked Dec 11 '25 08:12

Jesus Burneo Gutierrez


2 Answers

For jest users - just add the following code in setup-jest.js. Because jest needs to be initialized.

import { TestBed } from "@angular/core/testing";
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing";

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
like image 77
Deian Avatar answered Dec 12 '25 22:12

Deian


Is this using ng-packagr (i.e. an angular library)? If so you might want to check that there are no node_modules under the ./project/ folder.

This was throwing me this exact same error. The moment I deleted the node_modules under the project folder it all started to work again.

Source: https://github.com/ngneat/spectator/issues/546

like image 26
Wagner Danda da Silva Filho Avatar answered Dec 12 '25 22:12

Wagner Danda da Silva Filho