• 覆盖测试的依赖关系

    覆盖测试的依赖关系

    TestBed提供了几个函数,允许我们覆盖测试模块中使用的依赖项。

    • overrideModule
    • overrideComponent
    • overrideDirective
    • overridePipe

    例如,您可能想要覆盖组件的模板。这对于测试大型组件的一小部分很有用,因为您可以忽略DOM的其余部分的输出,并且只关注您感兴趣的部分。

    1. import {Component} from '@angular/core';
    2. @Component({
    3. selector: 'display-message',
    4. template: `
    5. <div>
    6. <div>
    7. <h1>{{message}}</h1>
    8. <div>
    9. </div>
    10. `
    11. })
    12. export class MessageComponent {
    13. public message: string = '';
    14. setMessage(newMessage: string) {
    15. this.message = newMessage;
    16. }
    17. }
    1. import {MessageComponent} from './message.component';
    2. import { provide } from '@angular/core';
    3. import {
    4. async,
    5. inject,
    6. TestBed,
    7. } from '@angular/core/testing';
    8. describe('MessageComponent', () => {
    9. let fixture;
    10. beforeEach(() => {
    11. TestBed.configureTestingModule({
    12. declarations: [MessageComponent],
    13. providers: []
    14. });
    15. fixture = TestBed.overrideComponent(MessageComponent, {
    16. set: {
    17. template: '<span>{{message}}</span>'
    18. }})
    19. .createComponent(MessageComponent);
    20. fixture.detectChanges();
    21. });
    22. it('should set the message', async(inject([], () => {
    23. fixture.componentInstance.setMessage('Test message');
    24. fixture.detectChanges();
    25. fixture.whenStable().then(() => {
    26. const compiled = fixture.debugElement.nativeElement;
    27. expect(compiled.querySelector('span').innerText).toEqual('Test message');
    28. });
    29. })));
    30. });

    View Example