Challenge
Encountering a problem where creating a new instance of a class within a unit test does not invoke the constructor.
Specifics
Attempting to validate if an error is raised when an incorrect server IP is provided, however, generating a new object of the class responsible for throwing the error does not yield the expected outcome.
The class under scrutiny is as follows:
export class ClassA {
private readonly _redisServerIP = config.redisServerIP;
private readonly _redisServerPort = config.redisServerPort;
constructor() {
console.log(this._redisServerIP);
this.configure();
}
private configure(): void {
this._redisSub = redis.createClient({host: this._redisServerIP, port: this._redisServerPort});
this._redisSub.on('error', (error) => {
if (error.code === "ECONNREFUSED") {
this._logger.error('Could not create a redisSub, is the redis server running?');
}
throw new Error('Something bad happened');
});
}
}
This represents my testing code:
import * as constants from '../src/config/config';
let socket;
let classA;
let httpServerAddr;
beforeAll((done) => {
classA = new ClassA();
httpServerAddr = classA.getServerIp();
done();
});
afterAll((done) => {
done();
});
beforeEach((done) => {
});
afterEach((done) => {
done();
});
describe('Socket.io redis testing', () => {
test('should fail due to invalid serverIP', () => {
constants.config.redisServerIP = "0.0.0.0";
classA = null;
expect(() => {
classA = new ClassA();
}).toThrow();
});
});
Only one instance of the server IP appears in my node console and the test fails with the following message:
expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.
Is this occurring because each test operates within its own promise? Could it be related to not clearing the existing instance of ClassA before initiating a new one?
======UPDATE======
Upon using breakpoints, I have discovered that the constructor does execute, but the log statement doesn't appear. The 'throw' statement never executes either. In the case of Redis, when an error occurs, an event named "error" is sent to the server, which doesn't seem to trigger during the test run. How can one wait for this event to be triggered?