Jasmine期待逻辑(期待A OR B)

nau*_*tur 35 javascript logic unit-testing jasmine

如果满足两个期望中的一个,我需要设置测试成功:

expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number));
expect(mySpy.mostRecentCall.args[0]).toEqual(false);
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number)).or.toEqual(false);
Run Code Online (Sandbox Code Playgroud)

我在文档中遗漏了什么,或者我是否必须编写自己的匹配器?

小智 46

将多个可比较的字符串添加到数组中然后比较.颠倒比较的顺序.

expect(["New", "In Progress"]).toContain(Status);
Run Code Online (Sandbox Code Playgroud)

  • 好主意,非常简洁!并给出比 `expect( Status == "New" || Status == "In Progress").toBe(true);` 更清晰的错误信息 (2认同)

Rob*_*ear 17

这是一个老问题,但万一有人还在寻找我还有另一个答案.

如何构建逻辑OR表达式并期待它?像这样:

var argIsANumber = !isNaN(mySpy.mostRecentCall.args[0]);
var argIsBooleanFalse = (mySpy.mostRecentCall.args[0] === false);

expect( argIsANumber || argIsBooleanFalse ).toBe(true);
Run Code Online (Sandbox Code Playgroud)

这样,您可以明确地测试/期望OR条件,并且您只需要使用Jasmine来测试布尔匹配/不匹配.可以在Jasmine 1或Jasmine 2中使用:)


rai*_*7ow 11

注意:此解决方案包含Jasmine v2.0之前版本的语法.有关自定义匹配器的更多信息,请参阅:https://jasmine.github.io/2.0/custom_matcher.html


Matchers.js只使用一个"结果修饰符" - not:

核心/ Spec.js:

jasmine.Spec.prototype.expect = function(actual) {
  var positive = new (this.getMatchersClass_())(this.env, actual, this);
  positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
  return positive;
Run Code Online (Sandbox Code Playgroud)

核心/ Matchers.js:

jasmine.Matchers = function(env, actual, spec, opt_isNot) {
  ...
  this.isNot = opt_isNot || false;
}
...
jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) {
  return function() {
    ...
    if (this.isNot) {
      result = !result;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以看起来你确实需要编写自己的匹配器(从一个before或一个it集合中正确this).例如:

this.addMatchers({
   toBeAnyOf: function(expecteds) {
      var result = false;
      for (var i = 0, l = expecteds.length; i < l; i++) {
        if (this.actual === expecteds[i]) {
          result = true;
          break;
        }
      }
      return result;
   }
});
Run Code Online (Sandbox Code Playgroud)