【问题标题】:How can I migrate my custom matchers from Jasmine 1 to Jasmine 2如何将我的自定义匹配器从 Jasmine 1 迁移到 Jasmine 2
【发布时间】:2017-03-11 04:29:56
【问题描述】:
不幸的是,JavaScript 测试框架 jasmine 的第 2 版引入了一些重大更改。其中一项更改是处理自定义匹配器的方式,如下所述:
http://jasmine.github.io/2.0/upgrading.html
addMatchers 函数不再位于规范 (this) 中,它现在位于全局 jasmine 对象中。
/* was:
this.addMatchers({
*/
jasmine.addMatchers({
现在匹配器的设置有点不同。工厂接收一个 util 对象,其中包含诸如 jasmines 相等函数和任何已注册的 customEqualityTesters 之类的东西。工厂应该返回一个带有比较函数的对象,该函数将直接使用实际值和预期值调用,而不是实际值在 this 上
/* was:
toBeCustom: function(expected) {
var passed = this.actual == expected;
*/
toBeCustom: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
var passed = actual == expected
比较现在应该返回一个具有 pass 和 message 属性的对象。
我正在寻找一种简单的方法来迁移我们现有的匹配器,以便我们可以轻松切换到新的 jasmine 版本。
【问题讨论】:
标签:
javascript
unit-testing
jasmine
【解决方案1】:
为了轻松过渡到新的 jasmine 版本,以下特殊迁移对象将有所帮助。
不是在 this 对象上添加匹配器,而是在 jasmineMigrate 对象上添加它们。但这确实是您需要做的。 jasmineMigrate 对象将负责其余的工作。
/* was:
this.addMatchers({
*/
jasmineMigrate .addMatchers({
迁移对象的实现:
var jasmineMigrate = {};
jasmineMigrate.addMatchers = function (matchers) {
Object.keys(matchers).forEach(function (matcherName) {
var matcher = matchers[matcherName],
migratedMatcher = {};
migratedMatcher[matcherName] = function (util, customEqualityTesters) {
return {
compare: function (actual) {
var matcherArguments,
thisForMigratedMatcher,
matcherResult,
passed;
//In Jasmine 2 the first parameter of the compare function
//is the actual value.
//Whereas with Jasmine 1 the actual value was a property of the matchers this
//Therefore modify the given arguments array and remove actual
matcherArguments = [].slice.call(arguments)
matcherArguments.splice(0, 1);
//Add actual to the this object we'll be passing to the matcher
thisForMigratedMatcher = {
actual: actual
};
//Now call the original matcher aufgerufen, with the modified
//arguments and thisForMigratedMatcher which will be applied to
//the matcher
passed = matcher.apply(thisForMigratedMatcher, matcherArguments);
matcherResult = {
pass: passed,
message: thisForMigratedMatcher.message
};
return matcherResult;
}
}
};
jasmine.addMatchers(migratedMatcher);
});
}