现在我正在为这种情况编写单元测试,如下所示:
public div: HTMLDivElement;
public currentEvent: EventType;
public listenToRender() {
this.adsService.render.filter((event: EventType) => {
return this.div.id === event.slot.getSlotElementId();
}).subscribe((event: EventType) => {
let custom_event = new CustomEvent('render', {
detail: event
});
this.currentEvent= event;
});
}
在单元测试期间,我用主题模拟渲染,但我不知道如何让它通过过滤器
return this.div.id === event.slot.getSlotElementId();
然后转到订阅功能。
class MockAdsService {
render = new Subject();
}
class MockEventType {
name: 'test_event';
slot: {
getSlotElementId = function() {return 'test_id'}
};
}
describe('test', () => {
let mockAdsService: MockAdsService,
mockEventType: MockEventType;
beforeEach(() => {
mockAdsService = new MockAdsService();
mockEventType = new MockEventType();
});
it('listenToRender fired correctly', () => {
mockAdsService.render.next(mockEventType);
component.listenToRender();
expect(component.currentEvent).toEqual(mockEventType);
});
});
我是否需要在subject.next中设置一些内容以传递过滤器?
答案 0 :(得分:1)
这非常简单。您的活动已经发生>>之后,您已订阅组件。冷可观察到的时间已经太晚了。只需切换render.next()
和component.listenToRender()
来电,一切都应该正常工作:
it('listenToRender fired correctly', () => {
component.listenToRender();
mockAdsService.render.next(mockEventType);
expect(component.currentEvent).toEqual(mockEventType);
});