我正在使用Angular 5与Jasmine和Karma。我正在尝试测试某个功能是否有效但我的订阅在单元测试期间没有触发。这导致我的单元测试失败,因为我正在使用jasmine的done函数。 我想让这个单元测试成功。
我将超时间隔设置为20秒,看是否只需要一段时间(不应该这样)。
我也试过使用async和fakeasync,但它不会触发。我有可能让订阅触发吗?
这是我得到的代码:
describe('FilterService', () => {
let service: FilterService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [FilterService]
});
service = TestBed.get(FilterService);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
});
it("SetItemsToFilterByAndApplyFilters should set ItemsToFilterBy and set the InFilter property", (done: DoneFn) => {
//arrange
let item1: any = new Organisation();
item1.Id = 1;
item1.InFilter = true;
let item2: any = new Organisation();
item1.Id = 2;
item1.InFilter = false;
let itemNew1: any = new Organisation();
itemNew1.Id = 1;
let itemNew2: any = new Organisation();
itemNew2.Id = 2;
service.SetItemsToFilterBy([item1, item2]);
let spy = spyOn(service.ItemsToFilterBy$, 'subscribe');
//act
service.SetItemsToFilterByAndApplyFilters([itemNew1, itemNew2]);
//assert
service.ItemsToFilterBy$.subscribe(result => {
let result1 = _.find(result, item => {
return item.Id == itemNew1.Id;
});
let result2 = _.find(result, item => {
return item.Id == itemNew2.Id;
});
expect(result1.InFilter).toBeTruthy();
expect(result2.InFilter).toBeFalsy();
done();
});
});
});
这是与Basavaraj Bhusani合作的代码
it("SetItemsToFilterByAndApplyFilters should set ItemsToFilterBy and set the InFilter property", (done: DoneFn) => {
//arrange
let spy = spyOn(service.ItemsToFilterBy$, 'subscribe').and.callThrough();
let item1: any = new Organisation();
item1.Id = 1;
item1.InFilter = true;
let item2: any = new Organisation();
item2.Id = 2;
item2.InFilter = false;
let itemNew1: any = new Organisation();
itemNew1.Id = 1;
let itemNew2: any = new Organisation();
itemNew2.Id = 2;
service.SetItemsToFilterBy([item1, item2]);
//act
service.SetItemsToFilterByAndApplyFilters([itemNew1, itemNew2]);
//assert
service.ItemsToFilterBy$.subscribe(result => {
let result1 = _.find(result, item => {
return item.Id == itemNew1.Id;
});
let result2 = _.find(result, item => {
return item.Id == itemNew2.Id;
});
expect(result1.InFilter).toBeTruthy();
expect(result2.InFilter).toBeFalsy();
done();
});
expect(spy).toHaveBeenCalled();
});
});
答案 0 :(得分:2)
如果service.ItemsToFilterBy$
为Subject<any>()
,而非BehaviorSubject
或ReplaySubject
,请在规范开头订阅service.ItemsToFilterBy$
。阅读here。
在监视某个方法时,使用callThrough()
方法jasmine
。
spyOn(service.ItemsToFilterBy$, 'subscribe')
即
const spy = spyOn(service.ItemsToFilterBy$, 'subscribe').and.callThrough();
在这里了解callThrough
https://jasmine.github.io/2.0/introduction.html