首页 > 解决方案 > Angular 2+ (7) 嵌套组件的浅测试

问题描述

好的,所以我有一个组件,我正在为其编写一些测试。在这个组件中,我有另一个具有输入的组件:

@Component({
  selector: 'navigator',
  templateUrl: './navigator.component.html',
  styleUrls: ['./navigator.component.scss'],
})
export class Navigator{

    @Input()
    public myobject: InputClass;
}

InputClass 是一个简单的对象:

export class InputClass{
    public id: string;
    public Name: any;

    constructor(id: string) {
        this.id = id;
    }
}

在主要组件中,我有相应的属性:

@Component({
      selector: 'main-component',
      templateUrl: './mainComponent.component.html',
      styleUrls: ['./mainComponent.component.scss'],
    })
    export class MainComponent{

         public myObject: InputClass;
    }

mainComponent 模板:

 <navigator class="container" [myobject] = "myObject">
 </navigator>

现在我想测试一下,如果我在 mainComponent 的 myObject 属性中设置了一些值,然后检查导航器中的 @Input 值是否已收到该值:

it('set the input in navigator',() => {
    let testobj: InputClass;
    testobj = {
        id: '1',
        componentName: 'SomeValue',
    };

    component.myObject= testobj;
    fixture.detectChanges();

    el = fixture.debugElement.query(By.css('navigator'));

    // For test and debug purposes
    let test = el.nativeElement.attributes['ng-reflect-myobject'];

    expect(test.value).toBe(testobj);
});

我之前用另一个输入但类型为字符串尝试过这个,当我设置它的值时,它就像一个魅力,但在这里它失败了,当我用 chrome 调试它时,我得到属性的值是 [object Object]:

测试结果

测试结果

调试信息

调试

现在我认为正在发生的是我得到了对象的字符串化版本(因为在 js 中它是从对象到字符串的默认转换,对吧?)。如果是这种情况,我如何从输入中获取对象?

标签: angularinputautomated-testsangular7angular-test

解决方案


您无法验证导航器 HTML 呈现的内容?

我相信在 renderHTML 中搜索字符串会简单得多,并且可以达到相同的测试效果。

在 Angular 测试文档中,他们使用 textContent 属性来做到这一点:Angular Testing - By CSS


推荐阅读