基于参数模拟具有不同返回值的Jest

时间:2020-05-05 18:14:45

标签: typescript jestjs

我正在努力寻找一种使用参数进行模拟的解决方案,并让所述模拟根据参数返回不同的值。我已经提出了以下解决方案,但是尽管可以工作,但感觉还是不太对。

任何以更清洁的方式完成此操作的建议将不胜感激。

jest.mock(
  'hooks/useResourceAttribute',
  () => (domain: string, type: string, id: string, attribute: string) => {
    let value: string = '';
    if (type === 'blah') {
      value = 'meh';
    }

    if (type === 'blah2') {
      value = 'meh2';
    }

    return {
      value,
      fetch: jest.fn(),
    };
  }
);

1 个答案:

答案 0 :(得分:0)

一种更灵活的方法是使用Jest间谍:

jest.mock('hooks/useResourceAttribute', () => jest.fn());

通过这种方式可以根据需要模拟值,从而导致更严格的测试:

const fetchMock = jest.fn();
...
useResourceAttribute.mockReturnedValue({ value: 'meh', fetch: fetchMock });

Jest内置间谍程序提供基本功能。对于更强大的间谍/存根,Sinn仍然可以单独或通过jest-sinon与Jest一起使用。 Sinon允许条件存根:

useResourceAttribute
  .withArgs('blah', sinon.match.any, sinon.match.any, sinon.match.any)
  .returns({ value: 'meh', fetch: fetchMock });

useResourceAttribute
  .withArgs('blah2', sinon.match.any, sinon.match.any, sinon.match.any)
  .returns({ value: 'meh2', fetch: fetchMock });