Created
August 8, 2022 17:08
-
-
Save kjendrzyca/c2f189331abcb5f45ce5b23a6c7bc3b8 to your computer and use it in GitHub Desktop.
Jest 26 fakeTimers and promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// figured out thanks to: | |
// https://stackoverflow.com/questions/52177631/jest-timer-and-promise-dont-work-well-settimeout-and-async-function/52196951 | |
// https://github.com/facebook/jest/issues/7151#issuecomment-622134853 | |
// https://stackoverflow.com/questions/51126786/jest-fake-timers-with-promises/51132058#51132058 | |
// https://github.com/facebook/jest/issues/2157 | |
// additional info | |
// https://github.com/facebook/jest/issues/10221#issuecomment-654687396 | |
// https://stackoverflow.com/questions/66391541/jest-advancetimersbytime-doesnt-work-when-i-try-to-test-my-retry-util-function | |
// https://gist.github.com/dwiyatci/740a52a08eb6147baa1f0be9b4f38785 | |
const flushPromises = () => new Promise(jest.requireActual("timers").setImmediate); | |
it('should throw an error in case the message sending fails', async () => { | |
// given | |
const expectedError = new Error('Send raw email failed') | |
const emailService = ({ | |
// using `async-retry` package to retry 3 times | |
sendRawEmail: jest.fn().mockRejectedValue(expectedError), | |
} as unknown) as EmailService; | |
const smsService = { sendSms: jest.fn() }; | |
const notificationService = notificationServiceFactory({ | |
emailService, | |
smsService, | |
}); | |
jest.useFakeTimers(); | |
// when | |
const sendingNotifications = notificationService.sendNotification({ | |
recipient, | |
subject, | |
message, | |
channels, | |
}); | |
await flushPromises().then(() => jest.runAllTimers()); // Progress 1st retry | |
await flushPromises().then(() => jest.runAllTimers()); // Progress 2nd retry | |
await flushPromises().then(() => jest.runAllTimers()); // Progress 2nd retry | |
// then | |
await expect(sendingNotifications).rejects.toEqual(expectedError); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment