Async and Jest — Lessons Learned

Di.rk
2 min readOct 7, 2021

--

or Did you forget to wait for something async in your test?

That was the output of my console lately, in detail:

Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log “[ { code: ‘Precipitation_Cum15min’ }, { code: ‘SurfaceWaterLevel’ } ] [Set Iterator] {
{ siteCode: null, code: ‘SurfaceWaterLevel’, from: null, to: null },
{ code: ‘Precipitation_Cum15min’ }

The reason for this, was the use of forEach in the context of async.

describe('all configurations', () => {
it('contains sites that are available', async () => {
configurationFiles.forEach(async fileName => {
const configuration = await import(`@/assets/${fileName}`)
// console.log(configuration)
const allSites = configuration.sites.map(({ code }) => code)
const result = await dataServices.getSites(allSites, abortController)
expect(result.length).toBe(allSites.length)
})
})

The problem with those constructs, you can’t wait for the Promise of the loop, its gone.

The solution is simple and straighforward. Replace the forEach with a for loop — in times of functional programming, not so nice, I think.

describe('all configurations', () => {
it('contains sites that are available', async () => {
for (const fileName of configurationFiles) {
const configuration = await import(`@/assets/${fileName}`)
// console.log(configuration)
const allSites = configuration.sites.map(({ code }) => code)
const result = await dataServices.getSites(allSites, abortController)
expect(result.length).toBe(allSites.length)
}
})

Hope this helps someone.

--

--

Di.rk
Di.rk

Written by Di.rk

Developer since the 80'th …

Responses (1)