茉莉花测试 Subject.subscribe

Jasmine Test Subject.subscribe

我有以下代码行

@Input() saveData: Subject<{ activeTab: string, callOnInit: boolean, Code: number, evnt: any }>;
ngOnInit() {

    // perform component logging
    this.performLogging();

    this.isAttachment = this.parentData.isAttachment;
    this.getOnloadData();
    if (this.saveData) {
        this.saveData.subscribe(v => {
            if (v && v.activeTab === 'attachment' && !v.callOnInit) {
                this.saveAttachment('parent', v.Code, v.evnt);
            } else if (v && v.activeTab === 'attachment' && v.callOnInit) {
                this.ngOnInit();
            }
       });
     }
}

如何编写测试用例覆盖里面的代码this.saveData.subscribe(v => {});

if (v && v.activeTab === 'attachment' && !v.callOnInit) {
            this.saveAttachment('parent', v.Code, v.evnt);
        } else if (v && v.activeTab === 'attachment' && v.callOnInit) {
            this.ngOnInit();
        }

下面是我使用 Jasmine & Karm 编写的测试用例。

it('should create', () => {
spyOn(component.saveData,'subscribe').and.callThrough();
component.saveData = new Subject();
component.saveData.next({
  activeTab: "",
  callOnInit: true,
  Code: 41,
  evnt: {}  
});    
fixture.detectChanges();
component.ngOnInit();    
expect(component.saveData.subscribe).toHaveBeenCalled();});

尝试创建实例后移动spyOn。

你的规格看起来不错。

你试过这样吗

it('should create', () => {
    spyOn(component.saveData,'subscribe').and.callThrough();
    component.ngOnInit();
    fixture.detectChanges();
    component.saveData = new Subject();
    component.saveData.next({
      activeTab: "",
      callOnInit: true,
      Code: 41,
      evnt: {}  
    });        
    expect(component.saveData.subscribe).toHaveBeenCalled();
});

下面的代码是覆盖内部黑色代码的正确代码 this.saveData.subscribe(v => {});

it('should create', () => {
  component.saveData = new Subject();
  spyOn(component.saveData,'subscribe').and.callThrough();
  component.ngOnInit();
  fixture.detectChanges();    
  component.saveData.next({
    activeTab: "",
    callOnInit: true,
    Code: 41,
    evnt: {}  
  });        
  expect(component.saveData.subscribe).toHaveBeenCalled();});