Print message on expect() assert failure

后端 未结 8 2189
一个人的身影
一个人的身影 2020-12-15 02:11

Is there a way to print a custom error message when a Jasmine expect() fails?

As an example, for end to end testing I have an array of web pages and I u

8条回答
  •  离开以前
    2020-12-15 02:56

    This is what I'm using for Jasmine 2.6.4 with TypeScript (Jasmine+Chutzpah in Visual Studio).

    The latest Jasmine version via NuGet seems to be 2.6.4 so I don't have the "withContext" thing (it also seems a bit of a clumsy way to do it, I prefer just to tag a message on the end of the matcher like many other frameworks).

    Even though the "expectationFailOutput" parameter (the message to display) is present in the jasmine.d.ts typings it seems it it not officially supported by jasmine:

    • https://github.com/jasmine/jasmine/issues/1457
    • https://github.com/jasmine/jasmine/issues/1682

    However, unofficially, it seems to work just fine for all except the toEqual matcher.

    I use the following to add a new toBeEqualTo matcher globally which I copied from the original toEqual matcher and simply add the expectationFailOutput message to the end. The interface declaration bit lets us use expect(...).toBeEqualTo(...) without TypeScript complaining.

    Example usage:

    expect(x).toBe(y, "Some Message"); // stock message works with .toBe
    expect(x).toEqual(y, "This is ignored"); // stock message ignored with .toEqual
    expect(x).toBeEqualTo(y, "My message is displayed"); // new matcher added below
    

    TypeScript implementation:

    /// 
    
    declare namespace jasmine
    {
        interface Matchers
        {
            toBeEqualTo(expected: any, expectationFailOutput?: any): boolean;
        }
    }
    
    beforeEach(function ()
    {
        jasmine.addMatchers({
            toBeEqualTo: function (util, customEqualityTesters)
            {
                customEqualityTesters = customEqualityTesters || [];
    
                return {
                    compare: function (actual, expected, expectationFailOutput)
                    {
                        var diffBuilder = (jasmine).DiffBuilder();
    
                        return {
                            pass: util.equals(actual, expected, customEqualityTesters, diffBuilder),
    
                            message: diffBuilder.getMessage() + ": " + expectationFailOutput
                        };
                    }
                };
            }
        });
    });
    

提交回复
热议问题