Search code examples
javascriptpromisequnitrsvp.jsrsvp-promise

How to run qunit assertions on resolving a Promise


I am writing a test for a function that returns a promise, and am not able to run assertions on resolving or rejecting the promise. I cannot use ES6 on this project so I am using the rsvp.js library which claims to implement the Promises/A+ specification. I am using the latest qunit version 1.17.1

The function under test:

var loadGroups = function(data) {
     return new RSVP.Promise(function(resolve, reject) {
        var groups = [];
        // ... some code to populate the groups array
        if(groups.length > 0) {
            resolve(groups);
        } else {
            reject("No groups were loaded");
        }
    });
};

The success test:

test('success test', function(assert) {
    assert.expect(1);

    var promise = loadGroups(testData);

    promise.then(function(groups) {
        assert.deepEquals(groups.length, 1);
    });

    return promise;
});

This fails with "Expected 1 assertions, but 0 were run"


The failure test:

test('failure test', function(assert) {
    assert.expect(1);

    var promise = loadGroups([]);

    promise.then(null, function(message) {
        assert.equals(message, "No groups were loaded");
    });

    return promise;
});

This fails with "Promise rejected during get promise when loading empty groups: No groups were loaded"


Solution

  • promises work by chaining. Promises are immutable wrappers over values.

    When you do:

    promise.then(function(e){
       // do something
    });
    

    You are not changing promise you are creating a new promise instead. Instead, you need to chain the promise:

    test('success test', function(assert) {
        assert.expect(1);
    
        var promise = loadGroups(testData);
    
        // return the `then` and not the original promise.
        return promise.then(function(groups) {
            assert.deepEquals(groups.length, 1);
        });
    
    });