猿问

如何在单元测试中注入 Input()?

所以我尝试对组件进行一些单元测试。但是我对 Input() 参数有一些问题。然后特别是组件中的一个组件


所以我有这个组件:



export class EcheqDisplayComponent implements OnInit {

  echeq: EcheqSubmissionApi;



  constructor(

    private route: ActivatedRoute

  ) {

    this.echeq = this.route.snapshot.data['submission'];

  }


  ngOnInit() {

  }


  getAnswers(page: EcheqPageApi): any[] {

    return page.elements.map(element => this.echeq.answers[element.name]);

  }

}


和模板:



<div class="echeq-display" *ngIf="echeq">

  <header class="echeq-display-header header">

    <div class="echeq-display-info">

      <h1 class="heading echeq-display-heading">

        {{ echeq.definition.title }}

      </h1>

      <div class="sub-heading echeq-display-subheading">

        <span class="echeq-display-creator">

          Toegekend door:

          {{ echeq.assignedByProfName ? echeq.assignedByProfName : 'Het Systeem' }}

        </span>

        <span class="echeq-display-date">{{

          echeq.definition.createdOnUtc | date: 'dd MMM'

        }}</span>

      </div>

    </div>

    <app-meta-box

      [metadata]="{

        numPages: echeq.definition.numPages,

        vPoints: echeq.definition.awardedVPoints

      }"

    ></app-meta-box>

  </header>

  <main class="echeq-display-questions body">

    <app-echeq-question

      *ngFor="let page of echeq.definition.pages; let i = index"

      [page]="page"

      [readonly]="true"

      [number]="i + 1"

      [answers]="getAnswers(page)"

    ></app-echeq-question>

  </main>

</div>


但它一直在说:


类型错误:无法读取未定义的属性“numPages”。


那么我必须改变它的工作原理吗?


哈士奇WWW
浏览 188回答 3
3回答

哆啦的时光机

你有你的错误 numPages: echeq.definition.numPages。Endeed,echeq也是未定义的。你可以试试 :component.echeq = {&nbsp; &nbsp;definition: {&nbsp; &nbsp; &nbsp;numPages: 9&nbsp; &nbsp;}}或者更好的方法是从this.route.snapshot.data['submission'];so返回这个值MockActivatedRoute更新:并更新MockActivatedRoute以允许动态参数:export class MockActivatedRoute {&nbsp; snapshot = {&nbsp; &nbsp; &nbsp; data: {}&nbsp; };&nbsp; constructor(){}&nbsp; withData(data:any): MockActivatedRoute {&nbsp; &nbsp; &nbsp;this.snapchot.data = data;&nbsp; &nbsp; &nbsp;return this;&nbsp;}}所以现在在你的测试中,你可以使用它:{ provide: ActivatedRoute, useValue: new MockActivatedRoute().withData({submission:{ answers:{} } }) }

慕尼黑8549860

没问题。这是一个简单的:beforeEach(async(() => {&nbsp; &nbsp; TestBed.configureTestingModule({&nbsp; &nbsp; &nbsp; providers: [&nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; imports:[&nbsp; &nbsp; &nbsp; &nbsp; ParticipantEcheqModule,&nbsp; &nbsp; &nbsp; &nbsp; RouterTestingModule&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; })&nbsp; &nbsp; .compileComponents();&nbsp; }));

江户川乱折腾

回答你的问题:component.metadata&nbsp;=&nbsp;///&nbsp;whatever&nbsp;you&nbsp;want&nbsp;this&nbsp;to&nbsp;be
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答