如何重置茉莉花里的间谍?

2022-02-23 00:00:00 jasmine javascript angular

我有一个问题,我已将模拟服务设置为间谍。

 mockSelectionsService = jasmine.createSpyObj(['updateSelections']);
然后,我调用了该存根方法两次,每次都是在不同的测试中。问题是,当我expect().toHaveBeenCalledWith()间谍.toHaveBeenCalledWith()的toHaveBeenCalledWith方法也包含它从第一个测试传递的参数时,该参数会在我的第二个测试中产生假阳性。

如何擦除/清除/重置下一个测试的spyObject,以便它根本不再认为它是被调用的?

服务/组件初始化

  beforeEach(() => {
    mockSelectionsService = jasmine.createSpyObj(['updateSelections']);

    TestBed.configureTestingModule({
      declarations: [QuickSearchComponent, LoaderComponent, SearchComponent, SearchPipe, OrderByPipe],
      providers: [OrderByPipe, SearchPipe, SlicePipe, {provide: SelectionsService, useValue: mockSelectionsService}],
      imports: [FormsModule, HttpClientModule]
    });


    fixture = TestBed.createComponent(QuickSearchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    fixture.componentInstance.templates = mockTemplates;
    fixture.componentInstance.manufacturers = mockManufacturers;
  });

解决方案

const spy = spyOn(somethingService, "doSomething");

spy.calls.reset();

这将重置已向间谍发出的呼叫。这样,您就可以在测试之间重用间谍。另一种方法是将测试嵌套在另一个describe()中,并将beforeEach()也放入其中。

相关文章