【问题标题】:Change component html template for each unit test in Angular为Angular中的每个单元测试更改组件html模板
【发布时间】:2020-10-30 00:16:26
【问题描述】:

有没有办法为每个测试更改组件html模板?

我在单元测试中创建了一个组件,我希望该组件的 html 模板在其他测试中有所不同。

我尝试使用 TestBed.overrideComponent (如代码所示)但出现错误:

“当测试模块已经被实例化时,不能覆盖组件元数据。

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

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    您可以创建一个单独的组件以使用新的 HTML 模板进行测试,然后在单元测试期间创建并使用该组件。使用 TestBed.createComponent()。

    但是,如果您在测试期间更改组件的 HTML 模板,我觉得您可能会以错误的方式处理此问题。相反,您想在 HTML 模板中使用变量,您想使用组件字段,然后在单元测试开始时设置该字段的值。

    您可以查看我在 Udemy 上的课程,了解更多关于 Angular 单元测试的信息,包括测试 HTML 模板!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 2020-04-19
      • 2021-07-01
      相关资源
      最近更新 更多