Jasmine expect logic (expect A OR B)

后端 未结 4 1666
执念已碎
执念已碎 2020-12-28 12:40

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.most         


        
相关标签:
4条回答
  • 2020-12-28 12:48

    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;
       }
    });
    
    0 讨论(0)
  • 2020-12-28 12:55

    Add multiple comparable strings into an array and then compare. Reverse the order of comparison.

    expect(["New", "In Progress"]).toContain(Status);
    
    0 讨论(0)
  • 2020-12-28 12:55

    You can take the comparison out of the expect statement to gain full use of comparison operators.

    let expectResult = (typeof(await varA) == "number" || typeof(await varA) == "object" );
    expect (expectResult).toBe(true);

    0 讨论(0)
  • 2020-12-28 13:08

    This is an old question, but in case anyone is still looking I have another answer.

    How about building the logical OR expression and just expecting that? Like this:

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

    This way, you can explicitly test/expect the OR condition, and you just need to use Jasmine to test for a Boolean match/mismatch. Will work in Jasmine 1 or Jasmine 2 :)

    0 讨论(0)
提交回复
热议问题