Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent unhandled promises in createAsyncThunk #570

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js']
}
4 changes: 4 additions & 0 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
process.on('unhandledRejection', error => {
// eslint-disable-next-line no-undef
fail(error)
})
15 changes: 15 additions & 0 deletions src/createAsyncThunk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,21 @@ describe('conditional skipping of asyncThunks', () => {
expect(dispatch).toHaveBeenCalledTimes(0)
})

test('does not fail when attempting to abort a canceled promise', async () => {
const asyncPayloadCreator = jest.fn(async (x: typeof arg) => {
await new Promise(resolve => setTimeout(resolve, 2000))
return 10
})

const asyncThunk = createAsyncThunk('test', asyncPayloadCreator, {
condition
})
const promise = asyncThunk(arg)(dispatch, getState, extra)
promise.abort(
`If the promise was 1. somehow canceled, 2. in a 'started' state and 3. we attempted to abort, this would crash the tests`
)
})

test('rejected action can be dispatched via option', async () => {
const asyncThunk = createAsyncThunk('test', payloadCreator, {
condition,
Expand Down
8 changes: 6 additions & 2 deletions src/createAsyncThunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,9 +326,12 @@ If you want to use the AbortController to react to \`abort\` events, please cons
)
)

let started = false
function abort(reason?: string) {
abortReason = reason
abortController.abort()
if (started) {
abortReason = reason
abortController.abort()
}
}

const promise = (async function() {
Expand All @@ -344,6 +347,7 @@ If you want to use the AbortController to react to \`abort\` events, please cons
message: 'Aborted due to condition callback returning false.'
}
}
started = true
dispatch(pending(requestId, arg))
finalAction = await Promise.race([
abortedPromise,
Expand Down