我有一个问题,我将模拟服务设置为间谍。
mockSelectionsService = jasmine.createSpyObj(['updateSelections']);
然后,我两次在不同的测试中两次调用该存根方法。问题是,当我用expect()
.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;
});
答案 0 :(得分:3)
类型1:
var myService = jasmine.createSpyObj('MyService', ['updateSelections']);
myService.updateSelections.calls.reset();
类型2:
var myService = spyOn(MyService, 'updateSelections');
myService.updateSelections.calls.reset();
注意:上面的代码已在Jasmine 3.5上进行了测试
答案 1 :(得分:2)
const spy = spyOn(somethingService, "doSomething");
spy.calls.reset();
这会将已经打过的电话重置为间谍。这样,您可以在测试之间重用间谍程序。另一种方法是将测试嵌套在另一个describe()
中,然后也将beforeEach()
放入其中。
答案 2 :(得分:1)
可以在beforeEach()中设置具有默认返回值的模拟服务,但是如果您想在以后更改模拟服务的响应,请不要在beforEach中调用夹具.detectChanges(),可以在每个规范中对其进行调用在应用了必要的更改(如果有)之后,如果您想更改特定规范中的模拟服务响应,则将其添加到该夹具之前的Fixture.detectChanges()
beforeEach(() => {
serviceSpy = jasmine.createSpyObj('RealService', ['methodName']);
serviceSpy.methodName.and.returnValue(defaultResponse);
TestBed.configureTestingModule({
providers: [{provide: RealService, useValue: serviceSpy }],
...
})
...
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
// do not call fixture.detectChanges() here
});
it('test something with default mocked service response', () => {
fixture.detectChanges();
....
});
it('test something with a new mocked service response', () => {
serviceSpy.methodName.and.returnValue(newResponse);
fixture.detectChanges();
....
});