mercredi 22 avril 2020

Angular's TestBed overrideComponent not working

I have an Angular directive that shows the element if the user has the appropriate permission. I want to test this using Jest.

I would like to change the template of the mock component for each test; one test with a valid permission and another test with an invalid permission.

I am trying to use the overrideComponent method to override the template for each test, but it is not working at all.

This is the spec file:

@Component({
  template: `<div></div>`
})
class TestDirectiveComponent {}

describe('Directive: pbmHasPermission', () => {
  let component: TestDirectiveComponent;
  let fixture: ComponentFixture<TestDirectiveComponent>;

  const mockAuthService = {
    getPermissions: jest
      .fn()
      .mockReturnValue([{ name: 'read_protocol' }, { name: 'add_protocol' }, { name: 'delete_protocol' }])
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TestDirectiveComponent, HasPermissionDirective],
      providers: [
        {
          provide: AuthService,
          useValue: mockAuthService
        }
      ]
    }).compileComponents();
  }));

  it('should show the element', () => {
    const template = `<button type="button" *pbmHasPermission="'add_protocol'">Add protocol</button>`;
    TestBed.overrideComponent(TestDirectiveComponent, { set: { template: template } });
    fixture = TestBed.createComponent(TestDirectiveComponent);
    fixture.detectChanges();
    component = fixture.componentInstance;
    expect(component).toBeTruthy();
    console.log(fixture.nativeElement.innerHTML); // prints <div></div> instead of the new template
  });
});

I tried many variations (using overrideTemplate, compiling the components, using then to execute after it...), which would only make reading the question more difficult, so I am willing to try everything you suggest, even if I already tried.

I am using Angular 8 and Jest 24.

Is it come kind of configuration problem? Is it because I use Jest? Am I doing something wrong?

Aucun commentaire:

Enregistrer un commentaire