jeudi 29 novembre 2018

No new class instance created after calling new class() within a jest test

Issue

Creating new class instance within unit test does not trigger the constructor.


Details

I am trying to test if an error is thrown when the wrong server IP is given, however when I try to create a new instance of the class that should throw the error it does not work.

The class I am trying to test is:

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 is my test 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', (done) => {
        constants.config.redisServerIP = "0.0.0.0";
        classA = null;

        expect(() => {
            classA = new ClassA();
            done();
        }).toThrow();
    });
});

I only see the server ip once in my node console and the test fails due to the following error:

expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.

Is this because every test runs in it's own promise? And when it's running in that said promise it can't log to the console? Or is it because of me not clearing the existing instance of ClassA before calling new ClassA()?

Aucun commentaire:

Enregistrer un commentaire