Jesus Burneo Gutierrez
Jesus Burneo Gutierrez

Reputation: 161

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?

Upvotes: 16

Views: 19300

Answers (6)

Patrick
Patrick

Reputation: 99

I was wondering over the described error message since all my tests worked the day before... It turned out that just deleting package-lock.json and all node modules (those from my workspace and the specific library) fixed the issue for me.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657078

To fix this error setup-jest.ts should consist of

import ‘jest-preset-angular/setup-jest.js’;

Upvotes: 2

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

Upvotes: 14

Mher
Mher

Reputation: 1253

The problem is that it must run everything from test.ts.

So instead of run ng test --main src/app/services/address/address.service.spec.ts command, just change const context = require.context('./', true, /\.spec\.ts$/); to const context = require.context('./', true, /address\.service\.spec\.ts$/); and use ng test command.

Upvotes: 0

Deian
Deian

Reputation: 1364

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());

Upvotes: 19

satanTime
satanTime

Reputation: 13539

the first thing: --main shouldn't be used, it points to an entrypoint, not to a desired test, and should be src/test.ts.

To run a single test use the next command:

ng test --include "app/services/address/address.service.spec.ts"

The test should be a bit different:

describe('AddressService', () => {
  let service: AddressService;
  let injector: TestBed;
  let httpTestingController: HttpTestingController;

  beforeEach(async () => {
    // let's compile TestBed first.
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [AddressService],
    }).compileComponents();

    // let's use TestBed.injector.
    service = TestBed.inject(AddressService);
    httpTestingController = TestBed.inject(HttpTestingController);
  });

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

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

  it('getAddress() should return data', () => {
    const dummyAddressListResponse = {
      data: [
        {direccion: 'address1'}, {Colas: 'queue1'},
        {direccion: 'address2'}, {Colas: 'queue2'}
      ],
    };

    let actual: any;
    service.getAddress().subscribe((res) => actual = res);

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

    expect(actual).toEqual(dummyAddressListResponse);
  });
});

Upvotes: 4

Related Questions