如何编写 Jasmine 自定义匹配器

How to write a Jasmine custom matcher

我正在尝试编写一个自定义匹配器来测试一个字符串是否包含不同字符串的特殊出现次数。这就是我所做的。

var matcher = {
    toContainTimes: function (expected, num) {
        return {
            compare: function(actual){
                actual.match(new RegExp(expected, "g") || []).length == num;
            }
        }
    }
}

但是我在执行这个的时候遇到了一个错误:

TypeError: Cannot read property 'pass' of undefined

我的测试是这样的:

expect(queryString).toContainTimes("&", 2);

如果字符串“&”在 queryString 中恰好出现两次,它应该 return 为真。 我做错了什么?

来自 Jasmine 文档:

The compare function must return a result object with a pass property that is a boolean result of the matcher. The pass property tells the expectation whether the matcher was successful (true) or unsuccessful (false).

您应该 return 声明具有此类属性的对象。

试试这个:

var matcher: {
    toContainTimes: function () {
        return {
            compare: function(actualValue, expectedResult){
                var expected = expectedResult[0];
                var num = expectedResult[1];
                var result = {
                    pass: true,
                    message: ''
                }
                result.pass = actualValue.match(new RegExp(expected, "g") || []).length === num;

                if(!result.pass)
                    result.message = 'insert error message here. this will shown when the jasmine spec failed';

                return result;
            }
        }
    }
}

用法:expect(queryString).toContainTimes(["&", 2]);