故事:
我们一直在使用自定义茉莉花匹配器来指望元素有一个手/指针光标:
beforeEach(function() {
jasmine.addMatchers({
toHaveHandCursor: function() {
return {
compare: function(actual) {
return {
pass: actual.getCssValue("cursor").then(function(cursor) {
return cursor === "pointer";
})
};
}
};
},
});
});
效果很好,使测试可读:
expect(queuePage.sortByButton).toHaveHandCursor();
问题:
当期望失败时,目前我们在控制台上以一种形式获得了一个完全无法读取的大块红色文本:
- 预期的ElementFinder({ptor_:Protractor({getProcessedConfig:Function,forkNewDriverInstance:Function,restart:Function, controlFlow:Function,schedule:Function,setFileDetector:Function, getSession:Function,getCapabilities:Function,quit:Function, actions:function,touchActions:Function,executeScript:Function, executeAsyncScript:Function,call:Function,wait:Function,sleep: 函数,getWindowHandle:Function,getAllWindowHandles:Function, getPageSource:Function,close:Function,getCurrentUrl:Function, getTitle:Function,findElementInternal_:Function, findElementsInternal_ ...滚动10分钟...,点击: 函数,sendKeys:Function,getTagName:Function,getCssValue: Function,getAttribute:Function,getText:Function,getSize: 函数,getLocation:Function,isEnabled:Function,isSelected: 功能,提交:功能,清除:功能,显示:功能, getOuterHtml:Function,getInnerHtml:Function,getId:Function, getRawId:Function,serialize:Function,takeScreenshot:Function}) 有手形光标。
问题:
为什么会这样? 我们如何改进匹配器并输出用户友好的错误呢? 类似的东西:
Expected 'auto' to be equal to 'pointer' cursor value.
根据我的理解,我们需要为自定义匹配器提供message
值,但我不完全确定如何传递实际元素cursor
CSS价值进入消息。以下是我到目前为止的情况:
toHaveHandCursor: function() {
return {
compare: function(actual) {
return actual.getCssValue("cursor").then(function(cursor) {
return {
pass: cursor === "pointer",
message: "Expected '" + cursor + "' to be equal to 'pointer' cursor value."
};
});
}
};
},
我希望这可行,但由于某种原因,我在测试运行后在控制台上看到相同的错误消息。
答案 0 :(得分:3)
我们在控制台上得到的是自动生成的jasmine matcher失败消息,它由ElementFinder
实例字符串表示组成 - 也就是说,它因某种原因出现,相当巨大。
现在,为了改进失败的消息,我们需要在message
旁边使用pass
密钥。我们应该考虑getCssValue()
返回一个承诺,并且需要解析一个实际的cursor
值,以便在自定义错误消息中使用:
toHaveHandCursor: function() {
return {
compare: function(actual) {
var result = {};
result.pass = actual.getCssValue("cursor").then(function(cursor) {
result.message = "Expected '" + cursor + "' to be equal to 'pointer' cursor value.";
return cursor === "pointer";
});
return result;
}
};
},
现在,如果期望失败,我们会得到一条很好的错误消息:
- Expected 'auto' to be equal to 'pointer' cursor value.
答案 1 :(得分:2)
你是对的,要设置自定义消息,你应该设置返回对象的message
属性。
该消息只是一个常规字符串。如果在履行承诺后将结果对象放在一起,则可以使用cursor
变量的值。
请参阅以下示例如何完成:
beforeEach(function(){
jasmine.addMatchers({
toBeDeactivated: function() {
return {
compare: function(account){
var accountStatusCode = account.get('status').statusCode;
var result = { pass: accountStatusCode === 5 };
if(result.pass) {
result.message = "Expected account with status code '" + accountStatusCode + " NOT to be deactivated.";
} else {
result.message = "Expected account with status code '" + accountStatusCode + "' to be deactivated.";
}
return result;
}
}
}
}
});
用承诺取代account.get()
应该很简单。