这是恢复模拟功能的 Jest 方式

Which is Jest way for restoring mocked function

在 Sinon 的存根中,恢复功能非常容易。

const stub = sinon.stub(fs,"writeFile",()=>{})
...
fs.writeFile.restore()

我希望用 Jest 做同样的事情。我得到的最接近的是这个丑陋的代码:

const fsWriteFileHolder = fs.writeFile
fs.writeFile = jest.fn()
...
fs.writeFile = fsWriteFileHolder 

如果你想clear all the calls到mock函数,你可以使用:

const myMock = jest.fn();
// ...
myMock.mockClear();

clear everything存储在mock中,请尝试改为:

myMock.mockReset();

感谢@nbkhope 的贡献,我终于找到了一个可行的解决方案。

因此以下代码按预期工作,即模拟代码然后恢复原始行为:

const spy = jest.spyOn(
    fs,
    'writeFile' 
  ).mockImplementation((filePath,data) => {
  ...
})
...
spy.mockRestore()

jest.spyOn() 在 mocking 和 unmocking 方法时很有用,但是在某些情况下你可能想要 mock 和 unmock esModule。

我最近遇到过这种情况,我发现这个解决方案适合我:

// Module that will be mocked and unmocked
import exampleModule from 'modules/exampleModule';

const ActualExampleModule = jest.requireActual('modules/exampleModule');

describe('Some tests that require mocked module', () => {
  // Tests on mock
});

describe('Some tests that require original module', () => {
  it('Test with restored module', async () => {
    const restoredModule = await import('modules/exampleModule');
    restoredModule.default = ActualExampleModule .default;

    // Now we can assert on original module
  });
});