diff --git a/README.md b/README.md index 92a9edc..29e19f1 100644 --- a/README.md +++ b/README.md @@ -485,3 +485,43 @@ describe('testing api', () => { }) }) ``` + +### Using functions to mock slow servers + +By default you will want to have your fetch mock return immediately. However if you have some custom logic that needs to tests for slower servers, you can do this by passing it a function and returning a promise when your function resolves + +```js +// api.js + +import 'cross-fetch' + +export function APIRequest(who) { + if (who === 'facebook') { + return fetch('https://facebook.com') + } else if (who === 'twitter') { + return fetch('https://twitter.com') + } else { + return fetch('https://google.com') + } +} +``` + +```js +// api.test.js +import { APIRequest } from './api' + +describe('testing timeouts', () => { + it('resolves with function and timeout', async () => { + fetch.mockResponseOnce( + () => new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }))), + 100 + ) + try { + const response = await request() + expect(response).toEqual('ok') + } catch (e) { + throw e + } + }) +}) +```