問題描述
對于某些測試場景,我需要針對多個值進行測試,這些值都可以.
For some test scenarios I run into the need of testing against multiple values which are all OK.
我想做的事情如下:
expect(resultCode).toBeIn([200,409]);
當 resultCode
為 200
或 409
時,此規(guī)范應通過.這可能嗎?
This spec should pass when resultCode
is either 200
or 409
. Is that possible?
添加感謝 peter 和 dolarzo 指導我創(chuàng)建匹配器.我遇到了 addMatchers() 的問題.所以,最后我在 jasmine.js 中添加了以下內容:
ADDED Thanks to peter and dolarzo for pointing me towards creating matchers. I had problems with addMatchers(). So, in the end I added the following to the jasmine.js:
jasmine.Matchers.prototype.toBeIn = function (expected) {
for (var i = 0; i < expected.length; i++)
if (this.actual === expected[i])
return true;
return false;
};
這給了我一個可行的解決方案.我現在可以根據需要做 toBeIn.(茉莉花1.3.1)
This gave me a working solution. I can now do the toBeIn as needed. (Jasmine 1.3.1)
推薦答案
為了做這樣的事情:
expect(3).toBeIn([6,5,3,2]);
Jasmine 有一個稱為匹配器的功能:
Jasmine has a feature called matchers:
這是一個關于如何聲明它們的示例.我在最后聲明了您正在尋找的方法:
This is an example on how to declare them. I have declared at the very end the method you are looking for:
describe('Calculator', function(){
var obj;
beforeEach(function(){
//initialize object
obj = new Object();
jasmine.addMatchers({
toBeFive: function () {
return {
compare: function (actual, expected) {
return {
pass: actual === 5,
message: actual + ' is not exactly 5'
}
}
};
},
toBeBetween: function (lower,higher) {
return {
compare: function (actual, lower,higher) {
return {
pass: ( actual>= lower && actual <= higher),
message: actual + ' is not between ' + lower + ' and ' + higher
}
}
};
},
toBeIn: function(expected) {
return {
compare: function (actual, expected) {
return {
pass: expected.some(function(item){ return item === actual; }),
message: actual + ' is not in ' + expected
}
}
};
}
});
});
這是你需要的匹配器:
toBeIn: function(expected) {
return {
compare: function (actual, expected) {
return {
pass: expected.some(function(item){ return item === actual; }),
message: actual + ' is not in ' + expected
}
}
};
}
重要與 jasmine 2.0.我必須將 jasmine.addMatchers({ 與 jasmine specrunner.html 一起使用,但是當我使用 Karma 對其進行配置時,我必須將 jasmine 替換為 this 之類的this.addMatchers({ 因為 Karma 使用早期版本的 Jasmine.
Important with jasmine 2.0. I had to use jasmine.addMatchers({ with jasmine specrunner.html but when I configured it with Karma I had to replace jasmine with this like this.addMatchers({ because Karma use an earlier version of Jasmine.
這篇關于Jasmine expect(resultCode).toBe(200 or 409)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!