【问题标题】:How to write a Jasmine custom matcher如何编写 Jasmine 自定义匹配器
【发布时间】:2015-04-27 12:05:09
【问题描述】:

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

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 中恰好出现两次,它应该返回 true。 我做错了什么?

【问题讨论】:

  • 你没有从你的匹配器return 任何东西。

标签: javascript testing jasmine matcher


【解决方案1】:

来自Jasmine docs:

比较函数必须返回一个带有pass的结果object 匹配器的 boolean 结果属性。通行证 属性告诉期望匹配器是否成功 (true) 或不成功 (false)。

您应该返回一个声明了此类属性的对象。

试试这个:

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]);

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多