如何扩展Jest模拟?

时间:2020-01-12 05:34:29

标签: typescript unit-testing mocking jestjs

在我的单元测试(用Typescript编写,由Jest运行)中,我想模拟两个具有共同功能的类。例如,它们都具有tick()getTicks()方法。目前,我的Jest模仿程序可以重复执行此操作的代码,如下所示:

const mock1 = jest.fn(() => {
  let ticks = 0;

  return {
    tick: jest.fn(() => {ticks++; }),
    getTicks: jest.fn(() => ticks),
    doSomething: jest.fn()
  }
});

const mock2 = jest.fn(() => {
  let ticks = 0;

  return {
    tick: jest.fn(() => {ticks++; }),
    getTicks: jest.fn(() => ticks),
    doAnotherThing: jest.fn()
  }
});

现在我可以做:

const mock1Instance = new mock1();
const mock2Instance = new mock2();
mock1Instance.tick();
mock2Instance.getTicks();

但是重复看起来很愚蠢。有没有办法让我声明基本的模拟,然后从其扩展,例如:

const baseMock = jest.fn(() => {
  let ticks = 0;

  return {
    tick: jest.fn(() => {ticks++; }),
    getTicks: jest.fn(() => ticks),
  }
});

2 个答案:

答案 0 :(得分:1)

如果您的baseMock看起来像这样:

const baseMock = () => jest.fn(() => {
  let ticks = 0;

  return {
    tick: jest.fn(() => {ticks++; }),
    getTicks: jest.fn(() => ticks),
  }
});

您可以使用baseMock属性和所需的新属性创建新对象:

const mock1Instance = {
  // note that new is not needed
  ...baseMock(),
  doSomething: jest.fn()
};

const mock2Instance = {
  ...baseMock(),
  doAnotherThing: jest.fn()
};

或者您可以从baseMock中创建它并分配它的属性

const mock1Instance = baseMock();
mock1Instance.doSomething = jest.fn();

答案 1 :(得分:0)

我目前正在做类似的事情,并且似乎可以正常工作(至少测试不会失败),但是我想听到更好的答案:

const baseMock = jest.fn(() => {
  let ticks = 0;

  return {
    tick: jest.fn(() => {ticks++; }),
    getTicks: jest.fn(() => ticks),
  }
});

const mock1 = jest.fn(() => {
  return {
    ...new baseMock(),
    doSomething: jest.fn()
  }
});

const mock2 = jest.fn(() => {
  return {
    ...new baseMock(),
    doAnotherThing: jest.fn()
  }
});

const mockInstance = new mock1();
mockInstance.tick(); // works ok