简体   繁体   中英

How to reset Jasmine Spy object?

Not able to find docs for resetting the Jasmine Spy object. If there is better way of using spy objects, please suggest.

// spec.js
import { mockService } from "./mockService"; // mockService = jasmine.createSpyObj(...)

describe('test', () => {
  beforeEach(function () {
    // NOTE: Following don't work

    // mockService.reset();
    // mockService.calls.reset();
    // mockService.method.calls.reset();
  });

  it('a', () => {
    mockService.fn();
    expect(mockService.fn).toHaveBeenCalledTimes(1);
  });

  it('b', () => {
    mockService.fn();
    expect(mockService.fn).toHaveBeenCalledTimes(1);
  });
});

It should work as expected.

Eg

const service = {
  fn() {},
};

const mockService = jasmine.createSpyObj(service, 'fn');

describe('test', () => {
  beforeEach(function () {
    mockService.fn.calls.reset();
  });

  it('a', () => {
    mockService.fn();
    expect(mockService.fn).toHaveBeenCalledTimes(1);
  });

  it('b', () => {
    mockService.fn();
    expect(mockService.fn).toHaveBeenCalledTimes(1);
  });
});

unit test results:

Randomized with seed 28798
Started
..


2 specs, 0 failures
Finished in 0.02 seconds
Randomized with seed 28798 (jasmine --random=true --seed=28798)
---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |      80 |     100 |                   
 index.spec.js |     100 |      100 |      80 |     100 |                   
---------------|---------|----------|---------|---------|-------------------

Incorrect way: spyObj.calls.reset()

Correct way: spyObj.spyMethod.calls.reset()

NOTE : calls.reset() is done for spy methods and not for spy object.

Jasmine reset() docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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