我在我的应用程序中提供了一个简单的服务......
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class WizardDialogNavigationService {
public navAction$: Observable<any>;
private navActionSubject: Subject<any> = new Subject();
constructor() {
this.navAction$ = this.navActionSubject.asObservable();
}
public navAction(action: string): void {
this.navActionSubject.next(action);
}
}
它不是最复杂的服务,它只允许我在组件之间进行通信。现在我需要对它进行测试,我不得不承认我对测试知之甚少。我只想检查当调用WizardDialogNavigationService.navAction
时navAction$
Observable包含传递的字符串,所以我写了以下内容......
import {TestBed, inject, async} from '@angular/core/testing';
import {Observable} from 'rxjs/Rx';
import {expect} from 'chai';
import * as sinon from 'sinon';
import {WizardDialogNavigationService} from './wizard-dialog-navigation.service';
describe('WizardDialogNavigationService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [WizardDialogNavigationService]
});
})
describe('navAction$ Observable', () => {
let sut: WizardDialogNavigationService; // sut = Service Under Test
beforeEach(inject([WizardDialogNavigationService], (service: WizardDialogNavigationService) => {
sut = service;
}));
it('should be the last passed value', async(() => {
const resultList = [];
sut.navAction('TestString');
sut.navAction$.subscribe((result) => resultList.push(result));
console.log(resultList); // output is []
expect(resultList.indexOf('TestString')).to.equal(0);
}));
});
});
我认为我错了,因为resultList数组不包含传递的值?就好像.next() .subscribe()
没有被调用/运行一样。如果有人能告诉我哪里出错了,我将不胜感激。
答案 0 :(得分:2)
如果您直接BehaviorSubject
,则需要subscribe
来返回已存储的值。
因此,您可以将Subject
更改为BehaviorSubject
并订阅它,然后就可以了。
文档:
https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md#behaviorsubject