how to spyon same method but two different parameters in jest?

Viewed 8397
    jest
      .spyOn(webService.prototype, 'isEnabled')
      .mockImplementation(() => {
        return Promise.resolve(true)
      })
    jest
      .spyOn(webService.prototype, 'isEnabled')
      .mockImplementation(() => {
        return Promise.resolve(false)
      })

So what I want is to return 'true' if parameter has 'YES' string in it. and return 'false' if parameter has 'NO' in it.

the typescript of function is like below..

  public isEnabled(featureId: string): Promise<boolean> {
    return this.toggle.isEnabled(featureId)
  }
2 Answers

jonrsharpe has the right idea in the comments. You can add a mock implementation to your spy and do something like

jest.spyOn(webService.prototype, 'isEnabled')
  .mockImplementation((yesOrNo: string) => {
    if (yesOrNo.includes('YES')) {
      return true;
    } else {
      return false;
    }
  });

And now it works for both the YES and NO parameter. Of course you can add on and tailor the logic more to your needs.

In addition to the last answer, I would create a utility function for mocking that method, this way you can initializate and clear this after each test execution, something like:

util:

const webServiceMock = {
  init(isEnabled) {
    jest.spyOn(webService.prototype, 'isEnabled')
      .mockImplementation(() => isEnabled);
  },
  destroy() {
    jest.clearAllMocks();
  }
};

tests:

describe('webService', () => {
  afterEach(() => {
    webServiceMock.destroy();
  });

  test('is enabled', () => {
    webServiceMock.init(true);
    expect(webService.isEnabled()).toBe(true);
  });

  test('is disabled', () => {
    webServiceMock.init(false);
    expect(webService.isEnabled()).toBe(false);
  });
});
Related