Search code examples
unit-testingpromisemocha.jschaichai-as-promised

Chai + mocha, succeed in test if resolved, fail if rejected


I have a function that returns a promise. In my test file that is using chai I want the following to happen:

const result = sendSurveyDataToAnalytics(userId,eventType,eventTitle)

result.then(() => {
    Logger.info("Succeed in the test if we get here")
}).catch(() => {
    Logger.info("Fail in the test if we get here")
});

the code explains it. Succeed in then, fail in catch. What is the proper way to do that with maybe expect, or should (already installed chai-as-promised)


Solution

  • If you're using chai-as-promised:

    const result = sendSurveyDataToAnalytics(userId, eventType, eventTitle);
    
    result.then(() => {
        Logger.info("Succeed in the test if we get here");
    }).catch(() => {
        Logger.info("Fail in the test if we get here");
    });
    
    it('resolves as promised', function() {
        return result.should.be.fulfilled;
    });
    
    // or:
    it('rejects as promised', function() {
        return result.should.be.rejected;
    });