How can I test that a value is "greater than or equal to" in Jasmine?

112,287

Solution 1

You just need to run the comparison operation first, and then check if it's truthy.

describe('percent',function(){
  it('should be a decimal',function(){

    var percent = insights.percent;

    expect(percent >= 0).toBeTruthy();
    expect(percent).toBeLessThan(1);

  });   
});

Solution 2

I figured I should update this since the API has changed in newer versions of Jasmine. The Jasmine API now has built in functions for:

  • toBeGreaterThanOrEqual
  • toBeLessThanOrEqual

You should use these functions in preference to the advice below.

Click here for more information on the Jasmine matchers API


I know that this is an old and solved question, but I noticed that a fairly neat solution was missed. Since greater than or equal to is the inverse of the less than function, Try:

expect(percent).not.toBeLessThan(0);

In this approach, the value of percent can be returned by an async function and processed as a part of the control flow.

Solution 3

The current version of Jasmine supports toBeGreaterThan and toBeLessThan.

expect(myVariable).toBeGreaterThan(0);

Solution 4

I'm late to this but posting it just in case some one still visits this question looking for answers, I'm using Jasmine version 3.0 and as mentioned by @Patrizio Rullo you can use toBeGreaterThanOrEqual/toBeLessThanOrEqual.

It was added in version 2.5 as per release notes - https://github.com/jasmine/jasmine/blob/master/release_notes/2.5.0.md

For e.g.

expect(percent).toBeGreaterThanOrEqual(1,"This is optional expect failure message");

or

expect(percent).toBeGreaterThanOrEqual(1);

Solution 5

Somewhat strangley this isn't basic functionality

You can add a custom matcher like this:

JasmineExtensions.js

yourGlobal.addExtraMatchers = function () {
    var addMatcher = function (name, func) {
        func.name = name;
        jasmine.matchers[name] = func;
    };

    addMatcher("toBeGreaterThanOrEqualTo", function () {
                   return {
                       compare: function (actual, expected) {
                           return {
                               pass: actual >= expected
                           };
                       }
                   };
               }
    );
};

In effect you're defining a constructor for your matcher - it's a function that returns a matcher object.

Include that before you 'boot'. The basic matchers are loaded at boot time.

Your html file should look like this:

<!-- jasmine test framework-->
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>

<!-- custom matchers -->
<script type="text/javascript" src="Tests/JasmineExtensions.js"></script>
<!-- initialisation-->
<script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>

Then in your boot.js add the call to add the matchers after jasmine has been defined but before jasmine.getEnv(). Get env is actually a (slightly misleadingly named) setup call.

The matchers get setup in the call to setupCoreMatchers in the Env constructor.

/**
 * ## Require &amp; Instantiate
 *
 * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
 */
window.jasmine = jasmineRequire.core(jasmineRequire);
yourGlobal.addExtraMatchers();

/**
 * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
 */
jasmineRequire.html(jasmine);

/**
 * Create the Jasmine environment. This is used to run all specs in a project.
 */
var env = jasmine.getEnv();

They show another way of adding custom matchers in the sample tests, however the way it works is to recreate the matcher(s) before every single test using a beforeEach. That seems pretty horrible so I thought I'd go with this approach instead.

Share:
112,287

Related videos on Youtube

Bryce Johnson
Author by

Bryce Johnson

front end developer

Updated on December 19, 2020

Comments

  • Bryce Johnson
    Bryce Johnson over 3 years

    I want to confirm that a value is a decimal (or 0), so the number should be greater than or equal to zero and less than 1.

    describe('percent',function(){  
    
      it('should be a decimal', function() {
    
        var percent = insights.percent; 
        expect(percent).toBeGreaterThan(0);
        expect(percent).toBeLessThan(1);
    
      });
    
    });
    

    How do I mimic " >= 0 "?

  • hashchange
    hashchange almost 9 years
    This works, but unfortunately, the message produced by a failing ">=" test is not particularly expressive ("expected false to be truthy"). And by the way, there is no need for the test to be async (ok, just nitpicking ;).
  • Vegar
    Vegar almost 9 years
    It contains a 'in range'-matcher, but not a 'greater or equal'/'less or equal' matcher, though...
  • TachyonVortex
    TachyonVortex over 8 years
    @hashchange With a plugin such as jasmine2-custom-message, the error message can be customised: since('expected percent to be greater than or equal to zero').expect(percent >= 0).toBeTruthy();
  • hashchange
    hashchange over 8 years
    @TachyonVortex Sounds interesting! I didn't know about that thing. For common comparisons like >=, I prefer a custom matcher because it keeps the tests uncluttered (easy enough to do, see my answer below), but for comparisons which come up less frequently, or are not expressive enough, that plugin seems to be exactly the right thing. Thanks!
  • Cyril CHAPON
    Cyril CHAPON over 8 years
    What about expect(percent).toBeGreaterThan(-1); xD I didn't try it
  • Sergei Panfilov
    Sergei Panfilov over 8 years
    This one should be accepted answer. Also: expect(2 + 2).not.toBe(5), expect(2 + 2).toBeGreaterThan(0), expect(2 + 2).toBeLessThan(5)
  • Broda Noel
    Broda Noel almost 8 years
    @Vegar, you can use expect(number).toBeGreaterThan(number);
  • Jonathan Parent Lévesque
    Jonathan Parent Lévesque over 6 years
    Which version of Jasmine do you use? I just upgrade from 2.6.2 to 2.8 and I still get the error TypeError: Cannot read property 'be' of undefined for expect(1).to.be.gte(-1);
  • stealththeninja
    stealththeninja over 6 years
    Question asked "greater than or equal to"
  • Deerled
    Deerled over 6 years
  • Kristian Hanekamp
    Kristian Hanekamp over 6 years
    This is dangerous, because expect(NaN).not.toBeLessThan(0); passes instead of failing. (not.toBeLessThan is only the inverse if you assume that percent is a Number. Otherwise, it is not the inverse.)
  • Rohit
    Rohit about 6 years
    Exactly as pointed by @KristianHanekamp the expect is not reliable as it also passes when value of 'percent' is not a Number (NaN).
  • TraxX
    TraxX about 6 years
    I think jasmine version > 2.3.4 does not execute specs in order. So if they want specs in order then they can create custom matchers but if they're okay with unordered specs then they can choose the above mentioned version.