Reputation: 782
I am stuck on writing a unit test for when the redisClient
fails for the createClient
call. Any idea on how I can write this. Below you will find what I have so far.
const asyncRedis = require("async-redis");
class redis {
constructor(redisHost, redisPort) {
this.redisHost = redisHost;
this.redisPort = redisPort;
}
async init() {
try {
this.redisClient = asyncRedis.createClient({
port: this.redisPort,
host: this.redisHost
});
} catch(error) {
console.log(`Error creating client due to: ${error}`)
}
}
}
module.exports = redis;
redis-test.js
test('init on error', async () => {
jest.mock('../../src/redis/redis')
const redis = require('../../src/redis/Redis');
redis.mockImplementation(() => {
return {
init: jest.fn(() => { throw new Error(); }
)};
})
expect(await redis.init()).toThrowError(Error());
})
Upvotes: 0
Views: 1256
Reputation: 2467
You are mocking your code, you should be mocking the async-redis
library code.
You need to mock the createClient
method to always throw an error. So that you can check your catch flow is executed.
This part, you got it right jest.fn(() => { throw new Error(); }
, always return an error.
I am no expert in NodeJS, sorry I am not able to provide detailed source code.
Upvotes: 1