【问题标题】:unit testing of many simple *ngIf许多简单 *ngIf 的单元测试
【发布时间】:2018-10-12 15:29:46
【问题描述】:

我有简单的组件

@Component({
    selector: 'app-certificate-panel',
    templateUrl: './certificate.component.html'
})
export class CertificateComponent {
    @Input()
    public certificate: Certificate;
}

带模板

<h3 translate>General</h3>
<x-form-row label="{{'Version' | translate}}">
    {{ certificate.version }}
</x-form-row>
<x-form-row label="{{'Serial Number' | translate}}">
    {{ certificate.serialNumber }}
</x-form-row>
<h3 translate>Issued From</h3>
<x-form-row label="{{'Common Name (CN)' | translate}}" *ngIf="certificate.issuedFrom.commonName">
    {{ certificate.issuedFrom.commonName }}
</x-form-row>
<x-form-row label="{{'Organization Unit (OU)' | translate}}" *ngIf="certificate.issuedFrom.organizationUnit">
    {{ certificate.issuedFrom.organizationUnit }}
</x-form-row>

显示了更多属性。这个模板中有几个*ngIf

现在我想编写单元测试。我应该测试每个*ngIf 吗?不是在测试框架功能吗?

【问题讨论】:

  • *ngIf 的输入来自哪里?
  • 我个人会对这段代码进行单元测试。模板层中的单元测试简单 ifs (ngIfs) 没有真正的收获。我通常从我的组件/服务/等中保留单元测试...而不是模板,并且模板逻辑是 e2e 测试中的测试。
  • @Aravind 它是在父组件中设置的@Input

标签: angular unit-testing typescript angular-test


【解决方案1】:

您可以使用此组件进行一系列可能的测试:

  1. 设置组件然后查询 DOM 元素以确保它们存在,就个人而言,如果 ngIfs 我不会这样做,但如果它很重要,那么你必须拨打电话,这是你的应用程序。
  2. 由于ngIf检查语句的真实性,单元测试语句,即:设置组件,检查所有这些语句的真实性。同样,根据上下文,由于这是从父级获取数据,因此您应该考虑如何确定这将被填充,并进行防御性编程。如果它有可能会损坏,只需进行这样的廉价测试即可。
  3. 有时测试ngIf 是没有意义的,就像我在2 中所说的那样,这可能是浪费时间,因为它要么是真实的要么不是真实的,所以如果你可以控制它,那么这个组件就非常简单。
  4. 您还可以在规范中创建一个父测试组件来进行集成测试,这非常复杂,但如果此组件树很关键或复杂,这通常是非常健壮的测试(个人很少这样做)。李>

上面的组件的好处是它很简单,因此测试也很简单。我个人会做选项 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2012-04-15
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多