2014-01-06 45 views
5

对于某些测试场景,我遇到了需要针对多个值进行测试的问题,这些都是正常的。茉莉花期待(resultCode).toBe(200或409)

我想要做的东西如下:当resultCode要么200409

expect(resultCode).toBeIn([200,409]); 

该规范应该通过。那可能吗?

ADDED 感谢peter和dolarzo指导我创建匹配器。我遇到了addMatchers()的问题。所以,最后我在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)

+0

尝试检出https://github.com/pivotal/jasmine/wiki/Matchers。 –

回答

6

为了使这样的工作:

expect(3).toBeIn([6,5,3,2]); 

茉莉花有一个功能叫做匹配器:

这是一个关于如何申报他们的例子。我宣布在最后,你要寻找的方法:

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 
          } 
         } 
        }; 
       } 

重要茉莉2.0。我不得不使用jasmine.addMatchers({茉莉花specrunner.html但是当我噶配置它,我曾与更换茉莉花this.addMatchers({因为噶使用茉莉花的早期版本

+0

匹配器是...感谢指针。我尝试了使用jasmine.addMatcher和this.addMatcher的建议。 ..都没有工作,我必须弄清楚为什么,我认为另一个问题会是最好的,因为它涉及requirejs/typescript。同时,我在原型中直接在jasmine.js中添加了一个新的匹配器,并且工作正常我更新了t他质疑我使用的结果。 – Paul0515

+0

万一它有帮助对于这个代码示例我使用了茉莉花2.0.0 – Dalorzo