【问题标题】:Do you always need a mock for ActivatedRoute?你总是需要一个模拟激活路由吗?
【发布时间】:2019-11-10 17:37:56
【问题描述】:

所以我正在做一些单元测试。我尝试对以下组件进行单元测试:

export class EcheqDisplayComponent implements OnInit {
  echeq: EcheqSubmissionApi;
  orgId = 1;

  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]);
  }


这是它的单元测试:


describe('EcheqDisplayComponent', () => {
  let component: EcheqDisplayComponent;
  let fixture: ComponentFixture<EcheqDisplayComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ],
      imports:[ParticipantEcheqModule,
        RouterModule.forRoot([])

      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EcheqDisplayComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  fit('should create component', () => {
    expect(component).toBeTruthy();
  });
});

所以我不会出错。

但我的问题是。这是做ti的正确方法吗?

因为对 ActivatedRoute 使用模拟不是更好吗?

如果是,那么正确的方法应该怎么做?

谢谢

所以这是它的模板:


<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>

和这样的单元测试:

 beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ],
      providers: [
        { provide: ActivatedRoute, useClass: MockActivatedRoute }
      ],
      imports:[
        ParticipantEcheqModule

      ]
    })
    .compileComponents();
  }));

这是 app-meta-box 组件:

export class MetaData {
  numPages: number;
  vPoints: number;
}

@Component({
  selector: 'app-meta-box',
  templateUrl: './meta-box.component.html',
  styleUrls: ['./meta-box.component.scss']
})
export class MetaBoxComponent implements OnInit {
  @Input() metadata: MetaData;

  constructor() {}

  ngOnInit() {}

}


【问题讨论】:

    标签: javascript angular unit-testing jasmine


    【解决方案1】:

    当调用“TestBed.configureTestingModule({...})”来配置测试模块时,您可以简单地提供模拟ActivatedRoute对象,并在“providers”属性中设置必要的变量。

    class MockActivatedRoute {
        public snapshot = { 
            data: {
               submission: {
                 answers: {}
               }
            }
        };
    }
    
    TestBed.configureTestingModule({
      declarations: [ ],
      providers: [
       { provide: ActivatedRoute, useClass: MockActivatedRoute }
      ]
      imports:[
        ParticipantEcheqModule,
        // RouterModule.forRoot([]) // Not required after mocking the "ActivatedRoute"
      ]
    })
    .compileComponents();
    

    这样你可以测试你的组件在activatedRoute中的不同值。

    【讨论】:

    • 感谢您的回答。但后来我会得到这个错误: TypeError: Cannot read property 'numPages' of undefined TypeError: Cannot read property 'numPages' of undefined at Object.eval [as updateDirectives] (ng:///ParticipantEcheqModule/EcheqDisplayComponent.ngfactory.js: 40:54)
    • 但是 asnware 属性是什么意思?
    • @savantCodeEngineer 被测组件中的“numPages”属性在哪里?我在 EcheqDisplayComponent 中没有看到它?您确定该错误仅与 EcheqDisplayComponent 组件有关>? “submission.answers”属性中是否需要“numPages”属性?
    猜你喜欢
    • 2017-01-15
    • 2011-09-13
    • 1970-01-01
    • 2011-04-16
    • 2019-05-03
    • 2015-09-19
    • 2015-10-24
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多