JasmineJS 'isNot' property

JasmineJS 'isNot' property

本文关键字:property isNot JasmineJS      更新时间:2023-09-26

关于jasmine.addMatchers的快速了解。使用git的最新Jasmine构建,进行自定义匹配的格式似乎与我在《Jasmine JavaScript测试》一书中看到的代码大不相同。书中有这样的代码:

this.actual or maybe even this.isNot

新格式类似于:

compare: function (actual, expected) {
    return {
        pass: some true or false statement...
    }
}

因此,在这种情况下,"this.actual"实际上是传入的参数"actual",这很酷。如果我们调用一个新的匹配器,比如:,访问isNot属性怎么样

expect(investment).not.toBeAGoodInvestment();

因此,在"toBeAGoodInvestment"的主体中,我们应该能够访问"isNot"属性。不知道如何使用新格式。我想好了如何将this.message从旧的方式设置为新的方式,如:

return {
    pass: some statement...,
    message: 'some message'
}

我们希望在jasmine报告中显示的消息将是动态的,基于"isNot"的设置。

在实际的Jasmine.js源代码中挖掘后,我发现了参数被传递到自定义匹配器的compare函数中的位置,事实上,"isNot"根本没有进入。"this.isNot"在Jasmine源中的"Expection.prototype.wrappCompare"函数的上下文中可用,但真正需要它的地方是我创建的自定义匹配器。

因此,现在在这个wrapCompare函数中,我只是在"if"语句中添加了args.push语句,如下所示:

if (this.isNot) {
    //-- Added this line
    args.push(this.isNot);
    matcherCompare = matcher.negativeCompare || defaultNegativeCompare;
}

现在,打电话给匹配者,我可以这样做:

expect(investment).not.toBeAGoodInvestment();

然后实际的匹配器会看起来像这样:

toBeAGoodInvestment: function () {
    return {
        compare: function (actual, isNot) {
            return {
                pass: actual.isGood(),
                message: 'Expected investment to be a ' + 
                   ((isNot) ? 'bad' :  'good') + ' investment'
            }
        }
    };
}

这是一个很好的小研究任务,可以弄清楚Jasmine在幕后做什么。

任何其他将"isNot"注入compare函数的方法,请告诉我。