5

Trying to mock Renderer2 in a Jest environment and can't make it working. Jest 23 & Angular 7. Tried everythig what goes from:

component.ts

const icosahedron = document.getElementById('renderIcosahedron');
this.renderer2.appendChild(icosahedron, this.renderer.domElement);

Getting all the time the error (only in tests):

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Edit: more detailed explanation has been added to the Angular's repo, however it was rejected as a bug. Link: https://github.com/angular/angular/issues/30865#issue-452458779

Daniel Danielecki
  • 8,508
  • 6
  • 68
  • 94

1 Answers1

1

Instead of creating the component object out of TestBed, you can call the component constructor as,

const renderer2 = { setStyle: () => {}, removeStyle: () => {} } as any;
    const myComponent: MyComponent= new MyComponent(
      {} as ChangeDetectorRef,
      renderer2 as Renderer2,
      {} as NgZone
    );

    const setStyleSpy = jest.spyOn(renderer2, "setStyle");

Let us say, If the renderer2 logic should be called in an async call, we can mock that async call function and test whether that function is called or not when async operation occur. Then the function can be invoked separately as part of other spec and test the rendering logic.

siddiq rehman
  • 145
  • 1
  • 2
  • 18