'How to test dependency injection Jest with inject Token Angular

I have the following test

describe('HttpClientService', () => {
  beforeEach(async () => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [],
      providers: [
        HttpClientService,
        { provide: HTTP_CLIENT, useClass: MockHttpClient }
      ]
    }).compileComponents()
    service = TestBed.inject(HttpClientService)
  })

  test('Should create service', () => {
    expect(service).toBeTruthy()
  })

  test('Should request post with correct url', fakeAsync(() => {
    service['_http'].post = jest.fn().mockReturnValue(of())
    const url = faker.internet.url()
    const body = faker.random.objectElement()
    service.post(url, body)
    tick()
    expect(service['_http'].post).toHaveBeenCalledWith(url, body)
  }))
})

Notice that I'm taking a direct reference from the dependency service['_http'].post = jest.fn().mockReturnValue(of()) I want to know if I can test dependency injection in a healthier way with testbed.inject(InterfaceInjector), or this is is best practices?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source