0

Here's my code:

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);
    const dialogElement = document.createElement('some-dialog');
    const componentRef = componentFactory.create(
      this.injector,
      [],
      dialogElement
    );
    document.body.appendChild(dialogElement);

This code is happening inside a service. Now, I'd like to grab the instance of the component (componentRef) from inside a test file. How can this be done, considering all I have in the test is the DOM element?

yccteam
  • 2,168
  • 4
  • 25
  • 47

1 Answers1

0

Ok. I've found a workaround for this. Because I'm the one who decides how my componentClass looks like (as a parameter to the function) I just need to make sure the componentClass exposes what I want in the test itself:

let componentInstance: DialogContentComponent;
@Component({
  template: `<h1 id="dialog-content">Hello</h1>`,
})
class DialogContentComponent {
  constructor() {
    componentInstance = this;
  }
}

And then the componentInstance will be the one generated inside the service.

A point to note - don't forget to reset the componentInstance in the beforeEach statement to make sure it doesn't carry from other tests.

yccteam
  • 2,168
  • 4
  • 25
  • 47
  • I think your workaround is fine.  But sounds like the code should belong to a component no? (maybe the service emits a message and a component which is in charge of adding stuff to the dom reacts?) – Shai Reznik - HiRez.io Feb 09 '21 at 21:32