从组件内部测试角度服务的订阅/取消订阅

时间:2019-04-01 16:14:54

标签: angular unit-testing angular-test angular-testing

我有这个页面组件类,仅在加载时调用服务,该服务填充了该服务内部的数组。在此组件上测试订阅和取消订阅功能的最佳方法是什么?

export class HomeComponent implements OnInit, OnDestroy  {
    private destroySubject$: Subject<void> = new Subject();

    constructor(private accountsService: AccountsService) {}

    ngOnInit(): void {
        this.accountsService.getLoginAndAccountsList$()
        .pipe(takeUntil(this.destroySubject$))
        .subscribe(() => { /* do nothing */ }, (error: Error) => {
            console.error('Unable to get the list of accounts!', error);
        });
    }

    ngOnDestroy(): void {
        this.destroySubject$.next();
    }
}

我现在的测试:

describe('Page Component: Home', () => {
    let component: HomeComponent;
    let fixture: ComponentFixture<HomeComponent>;
    let debugEl: DebugElement;
    let accountsService: AccountsService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [ HttpClientTestingModule,],
            providers: [ AccountsService ],
            declarations: [ HomeComponent]
        }).compileComponents();
        accountsService = TestBed.get(AccountsService);
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(HomeComponent);
        component = fixture.componentInstance;
        debugEl = fixture.debugElement;
    });

    it('should call the accountService to fetch the logins & accounts upon page load', async(() => {
        spyOn(accountsService, 'getLoginAndAccountsList$');
        fixture.detectChanges();
        expect(accountsService.getLoginAndAccountsList$).toHaveBeenCalled();
    }));

    it('should kill the accountService subscription upon page destruction', async(() => {
        spyOn(accountsService, 'getLoginAndAccountsList$');
        fixture.detectChanges();
        component.ngOnDestroy();
        expect(????).toHaveBeenCalled();
    }));
...

第一个测试现在正在工作,但是第二个没有,因为我不确定在那里需要进行什么测试。如何在调用ngOnDestroy时测试预订是否不再有效?

1 个答案:

答案 0 :(得分:1)

通常这是一个有效的问题,所以这是我的答案: 您可以通过监视观察者的下一个方法来测试订阅是否不再有效。并验证当observable发出新值时不再被调用。

让我详细说明:

在您的组件中,您拥有的位置:

String

在规范中,您应该具有以下内容:

equals

在您描述的特定用例中,我根本看不到需要使用可观察对象,因为您没有使用可观察对象发出的值。 您的服务可以具有在ngOnInit

中调用的填充函数
相关问题