mockResolvedValue在Jest/Typescript中的部分模拟上不是一个函数。

huangapple go评论66阅读模式
英文:

mockResolvedValue is not a function on partial mock with Jest/Typescript

问题

我正在尝试部分模拟一个模块,并根据某些测试需要设置模拟方法的返回值。

Jest抛出这个错误:

mockedEDSM.getSystemValue.mockResolvedValue 不是一个函数
TypeError: mockedEDSM.getSystemValue.mockResolvedValue 不是一个函数

我的模拟:

jest.mock('../src/models/EDSM', () => ({
  __esModule: true,
  ...jest.requireActual<typeof import('../src/models/EDSM')>('../src/models/EDSM'),
  getSystemValue: jest.fn(),
}));
const mockedEDSM = jest.mocked(EDSM);

在测试中:

it('应该测试', () => {
  mockedEDSM.getSystemValue.mockResolvedValue(edsmData);
});

在运行测试时,Typescript在IDE中没有警告,我只在Jest中得到错误。

英文:

I am trying to partially mock a module, and set the return value for the mocked method as needed in certain tests.

Jest is throwing this error:

mockedEDSM.getSystemValue.mockResolvedValue is not a function
TypeError: mockedEDSM.getSystemValue.mockResolvedValue is not a function

My mock:

jest.mock(&#39;../src/models/EDSM&#39;, () =&gt; ({
  __esModule: true,
  ...jest.requireActual&lt;typeof import(&#39;../src/models/EDSM&#39;)&gt;(&#39;../src/models/EDSM&#39;),
  getSystemValue: jest.fn(),
}));
const mockedEDSM = jest.mocked(EDSM);

Within tests:

it(&#39;should test&#39;, () =&gt; {
  mockedEDSM.getSystemValue.mockResolvedValue(edsmData);
});

Typescript is throwing no warnings in the IDE, I'm only getting errors from Jest when running the tests.

答案1

得分: 0

当然,发帖后立即找到了答案!在测试文件的顶部不需要调用jest.mock,唯一需要的是在每个测试中(或在before/after钩子中)对该方法进行spyOn

const getSystemValueMock =
  jest.spyOn(EDSM, 'getSystemValue')
  .mockResolvedValue(edsmData);
英文:

Ah of course, found the answer right after posting this!

No need to call jest.mock at the top of the test file, the only thing needed is to spyOn the method within each test (or in a before/after hook):

const getSystemValueMock =
  jest.spyOn(EDSM, &#39;getSystemValue&#39;)
  .mockResolvedValue(edsmData);

huangapple
  • 本文由 发表于 2023年5月18日 03:37:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定