Change component html template for each unit test in Angular

Viewed 612

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();
            ...
        });
    
    });

1 Answers

You can create a separate component for testing with the new HTML template and then create and use that component during the unit test. Using TestBed.createComponent().

But I feel like you are probably going about this in the wrong way if you are changing the HTML template of the component during tests. Instead, you want to use variables in the HTML templates, you want to use the components fields and then at the beginning of the unit test set the value of this field.

You can check out my course on Udemy to learn more about unit testing in Angular including testing HTML templates!

Related