Angular Testing- Can't resolve all parameters for MyOverlayRef: (?, ?, ?)

388 views Asked by At

I created a reusable overlay modal in angular based on the this blogs code. I have a file named overlay-ref.ts with code

export class MyOverlayRef<R = any, T = any> {
  constructor(
    public overlay: OverlayRef,
    public content: string | TemplateRef<any> | Type<any>,
    public data: T // pass data to modal i.e. FormData
  ) {}
}

As you can see it's not decorated with @Injectable, so when I use this file in my components I use it like this

export class CompanyContactOverlayComponent implements OnInit {
 
  constructor(public ref: MyOverlayRef){} 
 }

In my component it works but when I test the component I use it like this

beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [CompanyContactOverlayComponent],
      providers: [MyOverlayRef]
    })
    .compileComponents();
  });

It throws me an error Can't resolve all parameters for MyOverlayRef: (?, ?, ?). Saw many questions like this but can't find any answer.

My hunch is that since it's not an @injectable, I cannot use it in provider[].

Any way I can create an instance of it automatically and fix this Issue.

Edit In the service class, I'm creating a custom Injector to be Injected to ref-class

open<R = any, T = any>(
    content: string | TemplateRef<any> | Type<any>,
    data: T
  ): MyOverlayRef<R> {
    const configs = new OverlayConfig({
      hasBackdrop: true,
      scrollStrategy: this.overlay.scrollStrategies.block(),
    });

    const overlayRef = this.overlay.create(configs);

    const myOverlayRef = new MyOverlayRef<R, T>(overlayRef, content, data);

    const injector = this.createInjector(myOverlayRef, this.injector);

    overlayRef.attach(new ComponentPortal(OverlayModalComponent, null, injector));

    return myOverlayRef;
  }

  createInjector(ref: MyOverlayRef, inj: Injector) {
    const injectorTokens = new WeakMap([[MyOverlayRef, ref]]);
    return new PortalInjector(inj, injectorTokens);
  }
1

There are 1 answers

0
AliF50 On BEST ANSWER

Try providing a mock value for it.

const mockOverlayRef = {}; // add the properties that are required, here it is an empty object

beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [CompanyContactOverlayComponent],
      providers: [{ provide: MyOverlayref, useValue: mockOverlayRef }] // mock it like so.
    })
    .compileComponents();
  });