2020-10-30

Change component html template for each unit test in Angular

Is there a way to change the component html template for each test?

I created a component in my unit test and I want the component's html template to be different in other test.

I tried to use TestBed.overrideComponent (As shown in the code) but I got the error:

"Cannot override component metadata when the test module has already been instantiated."

@Component({
    template: `<div> <span *directive="let letter from ['x','y','z']"> </span> </div>`
})

class TestComponent {
    isEnabled: any;
}

describe('Directive', () => {

    let fixture: ComponentFixture<TestComponent>;
    let element: DebugElement;
    let component: TestComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestComponent, Directive],
        });
    });

    it('should do something with the initial component template', () =>{ ... });

    it('should do something with another template', () => {
        fixture = TestBed.overrideComponent(TestComponent, {
            set: {
                template: `<div> <span *directive="let letter from ['a','b','c'] enabled:isEnabled "> </span> </div>`
            }
        })
            .createComponent(TestComponent);
        component = fixture.componentInstance;
        component.isEnabled = true;
        fixture.detectChanges();
        ...
    });

});


from Recent Questions - Stack Overflow https://ift.tt/3kSStkE
https://ift.tt/eA8V8J

No comments:

Post a Comment