Skip to content

Commit

Permalink
Update readme with function example
Browse files Browse the repository at this point in the history
  • Loading branch information
jefflau committed Nov 29, 2018
1 parent 29cee8b commit ed6608f
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions README.md
Expand Up @@ -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
}
})
})
```

0 comments on commit ed6608f

Please sign in to comment.