茉莉花-返回值应始终在spyon函数中指定吗?

时间:2019-08-14 08:38:19

标签: angular jasmine karma-jasmine

我在UnitTest类中定义了以下模拟类:

class PersonServiceMock {
  public getPersons$ = () => of([]);
}

然后我有以下单元测试:

it('cancel - error CANCEL_NOT_AVAILABLE', fakeAsync(() => {
    const getPersonsSpy: jasmine.Spy = spyOn(TestBed.get(PersonService), 'getPersons$').and.returnValue(of([]));

    fixture.detectChanges();

    const debugElem: DebugElement = fixture.debugElement.query(By.css('app-detail-persons'));
    debugElem.triggerEventHandler('click', null);
    tick();
    expect(getPersonsSpy).toHaveBeenCalled();
  }));

问题是,为什么必须在spyOnreturnValue中定义与函数类中定义的相同的返回对象of([])?如果不这样,我将收到错误Cannot read property 'subscribe' of undefined

我认为,应该足够:

    const getPersonsSpy: jasmine.Spy = spyOn(TestBed.get(PersonService), 'getPersons$');

1 个答案:

答案 0 :(得分:1)

如果您正在使用Mock服务并将其添加到provider数组中,则不必使用spyOn方法。

只需添加

TestBed.configureTestingModule({
        providers: [
            { provide: PersonService, useClass: PersonServiceMock  }
        ],
        schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents().then(() => {
        fixture = TestBed.createComponent(someComponent);
        component = fixture.componentInstance;
        personService = TestBed.get(PersonService);
    });

每当组件的方法(比如说一个方法是“ somefunction”)调用getPersons $时,茉莉花都会在内部引用PersonServiceMock的getPersons $。

现在,您的单元测试用例如下:

it('cancel - error CANCEL_NOT_AVAILABLE', fakeAsync(() => {
    const debugElem: DebugElement = fixture.debugElement.query(By.css('app-detail-persons'));
    debugElem.triggerEventHandler('click', null);
    fixture.detectChanges();
    tick();
    expect(component.somefunction).toHaveBeenCalled();
  }));