简体   繁体   English

如何重置 Jasmine 中的间谍?

[英]How to reset a spy in Jasmine?

I have an issue where I've set up a mock service as a spy.我有一个问题,我将模拟服务设置为间谍。

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

I then call that stub method twice, each time in a different test.然后我两次调用该存根方法,每次都在不同的测试中。 The problem is that when i expect() the spy with .toHaveBeenCalledWith() the toHaveBeenCalledWith method also contains the arguments it was passed from the first test which produces a false positive on my second test.问题是,当我expect()使用.toHaveBeenCalledWith()的间谍时,toHaveBeenCalledWith 方法还包含 arguments 它是从第一个测试通过的,这在我的第二个测试中产生了误报。

How do I wipe/clear/reset the spyObject for my next test so that it no longer believes it as been called at all?如何擦除/清除/重置 spyObject 以进行下一次测试,使其不再相信它已被调用?

Initialisation of services/components服务/组件的初始化

  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();

This resets the already made calls to the spy.这会重置对间谍的已拨打电话。 This way you can reuse the spy between tests.这样你就可以在测试之间重用间谍。 The other way would be to nest the tests in another describe() and put a beforeEach() in it too.另一种方法是将测试嵌套在另一个describe()并在其中放置一个beforeEach()

Type 1:类型 1:

var myService = jasmine.createSpyObj('MyService', ['updateSelections']);

myService.updateSelections.calls.reset();


Type 2:类型 2:

var myService = spyOn(MyService, 'updateSelections');

myService.updateSelections.calls.reset();

Note: Code above is tested on Jasmine 3.5注意:以上代码在 Jasmine 3.5 上测试

The mock service with the default return value can be set in the beforeEach() , but if you want to change the mocked service response later, do not call fixture.detectChanges() in beforEach, you can call it in each spec after applying required changes (if any), if you want to change the mock service response in an specific spec, then add it to that spec before the fixture.detectChanges()可以在 beforeEach() 中设置默认返回值的模拟服务,但是如果你想稍后更改模拟的服务响应,不要在 beforEach 中调用 fixture.detectChanges(),你可以在应用 required 后在每个规范中调用它更改(如果有),如果您想更改特定规范中的模拟服务响应,请将其添加到该规范之前的 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();
      ....
  });

I use it like this:我这样使用它:

let service: anyTypeYouWant; 
let spyOnMethod: jasmine.Spy<(stringInput: string) => string>;

      beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(..Your_Inject..);
        spyOnMethod= spyOn(service, "myMethod");
      });


  it('Your Describe', () => {
   
    expect(service.myMethod).toHaveBeenCalled();
  })

add to Jelle's answer, if you got Cannot read property 'reset' of undefined when attempting mockSelectionsService.calls.reset() , try:添加到 Jelle 的答案中,如果您Cannot read property 'reset' of undefined when attempting mockSelectionsService.calls.reset()遇到Cannot read property 'reset' of undefined when attempting mockSelectionsService.calls.reset() ,请尝试:

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

reference: jest spyon demo: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname参考:jest spyon 演示: https ://jestjs.io/docs/en/jest-object#jestspyonobject-methodname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM