Jest assertion fails unless I console.log the expected value before the assertion (Code is not async)

While I cannot explain why the issue was happening, I managed to work around it by only calling expect() after the dispatch() call. I used a bunch of boolean flags that are set when the corresponding middleware stack is called.

The key is not to call expect(...) inside of a function that is passed as a parameter

This is what the correct test ended up being

test( "MiddlewareStack proceeds to next error-handling layer if 
next(error) is explicitly called", function() {
    const S = new MiddlewareStack();

    // Test flags
    let STD_HANDLER_WAS_CALLED = false;
    let FIRST_ERR_HANDLER_RECEIVED_ERROR = false;
    let FIRST_ERR_HANDLER_RECEIVED_CORRECT_ERROR = false;
    let SECOND_ERR_HANDLER_RECEIVED_ERROR = false;
    let SECOND_ERR_HANDLER_RECEIVED_CORRECT_ERROR = false;
    let SECOND_ERR_HANDLER_WAS_CALLED = false;

    S.use( () => {
        throw new Error( "PASS" );
    });

    S.use( ( err, data, next ) => {
        if( err ){
            FIRST_ERR_HANDLER_RECEIVED_ERROR = true;
            if( err.message === "PASS" )
                FIRST_ERR_HANDLER_RECEIVED_CORRECT_ERROR = true;
        }
        next( err )
    });

    S.use( ( data, next ) => {
        STD_HANDLER_WAS_CALLED = true;
    });

    S.use( ( err, data, next ) => {
        SECOND_ERR_HANDLER_WAS_CALLED = true;
        if( err ){
            SECOND_ERR_HANDLER_RECEIVED_ERROR = true;
            if( err.message === "PASS" )
                SECOND_ERR_HANDLER_RECEIVED_CORRECT_ERROR = true;
        }
    });

    S.dispatch();
    expect( FIRST_ERR_HANDLER_RECEIVED_ERROR ).toBe( true );
    expect( FIRST_ERR_HANDLER_RECEIVED_CORRECT_ERROR ).toBe( true );
    expect( STD_HANDLER_WAS_CALLED ).toBe( false );
    expect( SECOND_ERR_HANDLER_WAS_CALLED ).toBe( true );
    expect( SECOND_ERR_HANDLER_RECEIVED_ERROR ).toBe( true );
    expect( SECOND_ERR_HANDLER_RECEIVED_CORRECT_ERROR ).toBe( true );
});

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top