Redis tests don't exit after passing (using jest)
Asked Answered
Z

1

12

I implemented basic caching functionality for a project and ran into a problem during the testing. I test using jest and redis-mock and all the tests pass. The problem is when I import a file which imports the redis-file. The test-file doesn't exit.

Example:

index.test.js

import redis from 'redis'
import redis_mock from 'redis-mock'
jest.spyOn(redis, 'createClient').mockImplementation(red_mock.createClient)
import fileUsingRedis from './index'

describe('index', () => {
  it('should pass', () => expect(true).toBeTruthy())
}

index.js

import {set} from './redis'
export default function ...

redis.js

import redis from 'redis'
const client = redis.createClient()

export function set(key, value) {...}

'1 passed'...'Ran all test suites matching ...'

But then it keeps waiting, I assume because the redis.createClient() is async or something or other. Seeing as it happens on the import I can't just resolve it. Do I have to close the redis-instance connection after every test?

What is the solution/best-practice here?

Zackzackariah answered 17/5, 2018 at 9:2 Comment(1)
redis.createClient() opens a file handle, so jest waits for that handle to close. To know what handles are still open, you can run jest with the --detectOpenHandles flagKnap
Z
19

So yeah, closing the instance did it.

index.test.js

import redis from './redis'
...
afterAll(() => redis.closeInstance())

redis.js

export function closeInstance(callback) {
  client.quit(callback)
}
Zackzackariah answered 24/5, 2018 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.