代码之家  ›  专栏  ›  技术社区  ›  Rookie

摩卡承诺测试

  •  1
  • Rookie  · 技术社区  · 6 年前

    我在NodeJS中有以下测试代码:

    'use strict';
    
    // Example class to be tested
    class AuthController {
    
        constructor() {
            console.log('Auth Controller test!');
        }
    
        isAuthorizedAsync(roles, neededRole) {
            return new Promise((resolve, reject) => {
                return resolve(roles.indexOf(neededRole) >= 0);
            });
        }
    }
    
    module.exports = AuthController;
    

    'use strict';
    
    const assert         = require('assert');
    const AuthController = require('../../lib/controllers/auth.controller');
    
    describe('isAuthorizedAsync', () => {
        let authController = null;
    
        beforeEach(done =>  {
            authController = new AuthController();
            done();
        });
    
        it('Should return false if not authorized', function(done) {
            this.timeout(10000);    
    
            authController.isAuthorizedAsync(['user'], 'admin')
                .then(isAuth => {
                    assert.equal(true, isAuth);
                    done();
                })
                .catch(err => {
                    throw(err);
                    done();
                });
        });    
    });
    

     1 failing
    
    1) AuthController
        isAuthorizedAsync
          Should return false if not authorized:
      Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (c:\supportal\node_modules\ttm-module\test\controllers\auth.controller.spec.js)
    

    我已经尝试将默认的mocha测试超时增加到10秒,并确保承诺得到解决。我是新来摩卡的。我是不是漏了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   sripberger    6 年前

    mocha async API 正确地。使失败 done

    如前所述,你在 then 处理程序抛出,跳过第一个 完成 调用并转到 catch 处理程序反过来重新抛出相同的错误,同样地阻止您到达第二个错误 回拨。

    完成 ,导致mocha测试超时,可能会显示有关未处理拒绝的警告消息,具体取决于您使用的节点版本。

    最快的修复方法是正确使用done回调:

    it('Should return false if not authorized', function(done) {
        authController.isAuthorizedAsync(['user'], 'admin')
            .then(isAuth => {
                assert.equal(true, isAuth);
                done();
            })
            .catch(err => {
                done(err); // Note the difference
            });
    });
    

    it('Should return false if not authorized', function() {
        return authController.isAuthorizedAsync(['user'], 'admin')
            .then(isAuth => {
                assert.equal(true, isAuth);
            });
    });