Angular 5:如何在单元测试时处理组件依赖项的依赖项?

gjv*_*lya 5 unit-testing angular

我是 Angular 5 应用程序上下文中单元测试的新手。现在,我正在尝试对基本组件进行单元测试。

该组件称为 CardComponent,在该组件的 HTML 中,我将其称为 CheckboxComponent。
所以这是 CardComponent 的 HTML:

<div>
    <p>Test</p>
    <jg-checkbox [label]="'Test label'"></jg-checkbox>
</div>
Run Code Online (Sandbox Code Playgroud)

如您所见,没有什么复杂的事情发生。

但是, CheckboxComponent 确实注入了一个服务。对于这个问题,我将其称为 TestService。

因此,当我对 CardComponent 进行单元测试时,这是我的测试平台:

TestBed.configureTestingModule({
    declarations: [
        CheckboxComponent
    ]
}).compileComponents();
Run Code Online (Sandbox Code Playgroud)

然后我运行这个测试:

it('should create', () => {
    expect(component).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)

这只是通过 CLI 创建的默认测试。

但是现在,它抱怨 TestService 没有提供程序。我真的应该注入(和模拟/间谍)吗?

这似乎有点倒退,因为我只关心 CardComponent,我不应该关心 CheckboxComponent,对吧?这就是单元测试的全部意义所在。

否则,由于 Angular 具有分层组件,随着我的应用程序的增长,我可能不得不深入很多层次。

这不可能是对的。

有人可以帮忙解决这个问题吗?我感谢您的帮助!

jos*_*ish 3

If there's no need to reference the CheckboxComponent in the CardComponent, there are two approaches:

  • the CheckboxComponent can be stubbed
  • NO_ERRORS_SCHEMA can be used in TestBed.configureTestingModule({})

The documentation has a section about Nested component tests

There is also an answer concerning Shallow component tests

Stubbing

Create a stub component in card.component.spec.ts.

@Component({selector: 'jg-checkbox', template: ''})
class CheckboxStubComponent {}
Run Code Online (Sandbox Code Playgroud)

Then declare this in TestBed.configureTestingModule({}).

TestBed.configureTestingModule({
  declarations: [
    CardComponent,
    CheckboxStubComponent
  ]
})
Run Code Online (Sandbox Code Playgroud)

NO_ERRORS_SCHEMA

NO_ERRORS_SCHEMA can be used instead of stubs.

TestBed.configureTestingModule({
  declarations: [
    CardComponent
  ],
  schemas: [ NO_ERRORS_SCHEMA ]
})
Run Code Online (Sandbox Code Playgroud)

The NO_ERRORS_SCHEMA tells the Angular compiler to ignore unrecognized elements and attributes.

Either approach is acceptable. However, the documentation has a warning about overusing NO_ERRORS_SCHEMA.

The NO_ERRORS_SCHEMA also prevents the compiler from telling you about the missing components and attributes that you omitted inadvertently or misspelled. You could waste hours chasing phantom bugs that the compiler would have caught in an instant.

It also mentions that stubs have an additional advantage.

The stub component approach has another advantage. While the stubs in this example were empty, you could give them stripped-down templates and classes if your tests need to interact with them in some way.

It goes on further to show how to use both approaches together depending on the needs of the test.