【问题标题】:how to spyon same method but two different parameters in jest?如何在玩笑中窥探相同的方法但有两个不同的参数?
【发布时间】:2021-06-08 16:49:04
【问题描述】:
    jest
      .spyOn(webService.prototype, 'isEnabled')
      .mockImplementation(() => {
        return Promise.resolve(true)
      })
    jest
      .spyOn(webService.prototype, 'isEnabled')
      .mockImplementation(() => {
        return Promise.resolve(false)
      })

所以如果参数中包含“YES”字符串,我想要返回“true”。如果参数中包含“NO”,则返回“false”。

函数的打字稿如下..

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

【问题讨论】:

  • .mockImplementation((parameter) =&gt; ...)?

标签: typescript jestjs nestjs


【解决方案1】:

jonrsharpe 在 cmets 中有正确的想法。您可以为您的间谍添加一个模拟实现并执行类似的操作

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

现在它适用于YES 和NO 参数。当然,您可以根据自己的需要添加和调整逻辑。

【讨论】:

    【解决方案2】:

    除了最后一个答案,我会创建一个实用函数来模拟该方法,这样您就可以在每次测试执行后初始化并清除它,例如:

    实用程序:

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

    测试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-20
      • 2021-09-02
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多