Search code examples
angulartypescriptunit-testingjasmineangular-unit-test

Angular Tests. ProvidedIn: Module breaking


Currently I am using a service:

@Injectable({
  providedIn: MyModule
})
export class MyService {
 //... do stuff
}

---

@NgModule({
  declarations: [MyComp],
  imports: [
    ReactiveFormsModule,
    CommonModule,
    SharedModule,
    ComponentsModule,
    MyCompRoutingModule
  ],
  providers: [MyService]
})
export class MyModule {}

I have been hours trying to understand why I am getting a error:

MyComponent should exist FAILED TypeError: Cannot read properties of undefined (reading 'ɵcmp')

This only happens on Karma Jasmine unit tests. The code itself works marvellously!

Unfortunately I cannot use providedIn: 'root' but if I do use it though, I do not get the error. Same with the providedIn: 'any'

describe('MyComponent', () => {
  let component: MyComponent;
  let service: MyService;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        ComponentsModule,
        SharedModule,
        ReactiveFormsModule
      ],
      providers: [
        MyService,
        HttpService
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    service = TestBed.inject(MyService);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Any advice? Thanks in advance.


Solution

  • Providing in an NgModule is deprecated.

    providedIn: 'root' is the way to go 👌 !