How to test ES7 asynchronous function using mocha / chai / chai-as-promised

I have the following function to check:

// ...
const local = new WeakMap();

export default class User {

  // ...

  async password(password) {
    if (!password) return local.get(this).get('hash'); // remove this for security reasons!
    if (password.length < 6) throw new Error('New password must be at least 6 characters long');
    if (!password.match(passwordPattern)) throw new Error(`New password must match ${passwordPattern}`);
    local.get(this).set('hash', await Password.hash(password));
  }

  // ...

}

Now I want to test this function with mocha , chai and chai-as-promised :

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';

import User from '../../../server/User';

chai.use(chaiAsPromised);
const expect = chai.expect;

describe('.password()', () => {

  const testuser = new User({username: 'Testuser', password: '123abc'});

  // FINDME
  it(`should throw when too short`, () => {
    return expect(testuser.password('1a')).to.eventually.throw();
  });

  // ...

});

Look for the comment // FINDMEin the code above to get the context I'm referring to.

, , , async password(). , async ECMAScript7 thenable, , chai-as- . , , , expect().

: babel, :

babel-node --experimental node_modules/mocha/bin/_mocha --watch --recursive -R spec --check-leaks

Babel 6:

babel- node 6.4.0, :

npm install --save-dev babel-preset-stage-0

:

./node_modules/.bin/babel-node --presets stage-0 node_modules/mocha/bin/_mocha --    
recursive -R spec --check-leaks
+4
2

, eventually.throw() .be.rejected chai-as-, async function Promise. . github, .

+4

, ""

, "done"

" Mocha ! , . ( )() Mocha , ." https://mochajs.org/

describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(function(err, result) {
        if (err) throw err;
        done();
      });
    });
  });
});
0

All Articles