3

我正在尝试为 Jasmine 实现一个自定义匹配器,我想检查给定的对象属性值是否在其他两个对象属性值的范围内。

这是我到目前为止得到的:

let matcher = {
            toLieWithin: function (util: jasmine.MatchersUtil, customEqualityTesters: Array<jasmine.CustomEqualityTester>): jasmine.CustomMatcher {
                return {
                    compare: function (actual: any, expected: any): jasmine.CustomMatcherResult {
                        let result: jasmine.CustomMatcherResult = {
                            pass: false,
                            message: ''
                        };

                        result.pass = liesWithin(actual, expected);

                        return result;
                    }
                }
            }
        }; 

function liesWithin<T>(objActual: T, objExpected: T[]): boolean {
        let output: boolean;
        if(objExpected) {
          output = objActual.x > objExpected[0].x && objActual.x < objExpected[1].x && objActual.y > objExpected[0].y && objExpected[1].y;
        }
return output;    
}

在这里,我假设,实际有两个属性xy. 并且预期是一个由两个对象组成的数组,每个对象也有两个属性xy

actual = {x: -5, y: -10}; expected = [{x: -10, y: -17},{x: 0, y: 0}];

现在,我相信对于上面给出的简单示例,这种情况是可行的。但是当我试图将它实现为泛型时,我如何找到该对象具有哪些属性?我的方法正确吗?谁能给我一些想法,我该如何实施这种方法。

谢谢你。

4

1 回答 1

4

It looks like you're on the right track with your liesWithin function, you just need to account for the situation where the expected object may not come back ordered how you expect. This code should cover those situations as well:

// Helper to reduce repeated code
function isWithinRange(val, a, b) {
    return (val > a && val < b) || (val > b && val < a);
}

function liesWithin<T>(objActual: T, objExpected: T[]): boolean {
    if (objExpected) {
        let props = Object.keys(objActual);
        // Splitting X and Y checks into two for readability
        let isInYRange = isWithinRange( objActual[ props[0] ], objExpected[0][ props[0] ], objExpected[1][ props[0] ] );
        let isInXRange = isWithinRange( objActual[ props[1] ], objExpected[0][ props[1] ], objExpected[1][ props[1] ] );
        return isInXRange && isInYRange;
    }
    return;
}
于 2018-04-11T21:02:16.340 回答