How to test promises with Mocha

前端 未结 2 1625
春和景丽
春和景丽 2020-12-05 20:39

I\'m using Mocha to test an asynchronous function that returns a promise.

What\'s the best way to test that the promise resolves to the correct value?

2条回答
  •  甜味超标
    2020-12-05 21:02

    Then 'returns' a promise which can be used to handle the error. Most libraries support a method called done which will make sure any un-handled errors are thrown.

    it('does something asynchronous', function (done) {
      getSomePromise()
        .then(function (value) {
          value.should.equal('foo')
        })
        .done(() => done(), done);
    });
    

    You can also use something like mocha-as-promised (there are similar libraries for other test frameworks). If you're running server side:

    npm install mocha-as-promised
    

    Then at the start of your script:

    require("mocha-as-promised")();
    

    If you're running client side:

    
    

    Then inside your tests you can just return the promise:

    it('does something asynchronous', function () {
      return getSomePromise()
        .then(function (value) {
          value.should.equal('foo')
        });
    });
    

    Or in coffee-script (as per your original example)

    it 'does something asynchronous', () ->
      getSomePromise().then (value) =>
        value.should.equal 'foo'
    

提交回复
热议问题