Skip to content

Commit 240c537

Browse files
jefflauloris
authored and
loris
committed
Update readme with function example
1 parent b3ea257 commit 240c537

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

README.md

+40
Original file line numberDiff line numberDiff line change
@@ -485,3 +485,43 @@ describe('testing api', () => {
485485
})
486486
})
487487
```
488+
489+
### Using functions to mock slow servers
490+
491+
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
492+
493+
```js
494+
// api.js
495+
496+
import 'cross-fetch'
497+
498+
export function APIRequest(who) {
499+
if (who === 'facebook') {
500+
return fetch('https://facebook.com')
501+
} else if (who === 'twitter') {
502+
return fetch('https://twitter.com')
503+
} else {
504+
return fetch('https://google.com')
505+
}
506+
}
507+
```
508+
509+
```js
510+
// api.test.js
511+
import { APIRequest } from './api'
512+
513+
describe('testing timeouts', () => {
514+
it('resolves with function and timeout', async () => {
515+
fetch.mockResponseOnce(
516+
() => new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }))),
517+
100
518+
)
519+
try {
520+
const response = await request()
521+
expect(response).toEqual('ok')
522+
} catch (e) {
523+
throw e
524+
}
525+
})
526+
})
527+
```

0 commit comments

Comments
 (0)