Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - Jasmine expect logic (expect A OR B)

I need to set the test to succeed if one of the two expectations is met:

expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number));
expect(mySpy.mostRecentCall.args[0]).toEqual(false);

I expected it to look like this:

expect(mySpy.mostRecentCall.args[0]).toEqual(jasmine.any(Number)).or.toEqual(false);

Is there anything I missed in the docs or do I have to write my own matcher?

question from:https://stackoverflow.com/questions/13530365/jasmine-expect-logic-expect-a-or-b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note: This solution contains syntax for versions prior to Jasmine v2.0. For more information on custom matchers now, see: https://jasmine.github.io/2.0/custom_matcher.html


Matchers.js works with a single 'result modifier' only - not:

core/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;

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

So it looks like you indeed need to write your own matcher (from within a before or it bloc for correct this). For example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...