'Is there any way to mock API responses using snapshots?

I'm currently trying to find a good way to mock API responses for a subset of end-to-end tests, and was thinking it would be swell if there was a way to take snapshots when the backend services are healthy, and then use those snap-shotted responses in place of making actual HTTP requests when the tests are being run. Does anyone know if a library exists for this sort of thing?

Basically, I'd like to do something like the following:

it('does something', () => {
  const data = process.env.UPDATE_SNAPSHOTS ? getDataFromServer() : getDataFromSnapshot();
  saveSnapshot(data); // Saves snapshot data to file system like jest
  
  // Test things using "data"
});

It would be great if I could just use jest for this, since I'm using jest anyway. But as far as I can tell, jest doesn't have any file-based snapshot methods besides toMatchSnapshot() and I really need to be able to saveSnapshot() and readSnapshot() arbitrarily.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source