javascript - 如何使用 Mocha 测试 Javascript Singleton

标签 javascript singleton mocha.js

我是 Javascript 新手,我想创建单元测试来测试单例。

所以我在authentication.js 文件中有以下单例:

var AuthenticationService = (function () {

  /**
   * Instance du singleton
   */
  var instance;

  /**
   * Private property du service d'authentification de firebase.
   * @type {firebase.auth.Auth}
   */
  var privateFirebaseAuthService = null;

  function init(firebaseAuthService) {

    privateFirebaseAuthService = firebaseAuthService;

    /**
     * Crée un nouvel utilisateur de l'application
     * @param  {String} email    l'email de l'utilisateur
     * @param  {String} password le password de l'utilisateur
     * @return {Promise<firebase.User>}          Renvoie l'utilisateur créé en cas de succès.
     */
    function privateCreateUserAsync(email, password) {
      return new Promise(function(resolve, reject){
        if(privateFirebaseAuthService === null){
          console.log("Le service d'authentification firebase n'est pas initialisé.");
          reject(Error(Enum.Authentication.CreateUserErrorCode.AuthenticationServiceNotInitialized));
        }

        privateFirebaseAuthService.createUserWithEmailAndPassword(email, password)
          .then(function(firebaseUser) {
            console.log("createUserAsync ok " + email);
            // TODO : renvoyer un application user plutôt qu'un user firebase.
            resolve(firebaseUser);

          })
          .catch(function(error) {
            var errorCode = error.code;
            console.log("createUserAsync KO " + errorCode);

            if (errorCode == 'auth/email-already-in-use') {
              reject(Error(Enum.Authentication.CreateUserErrorCode.EmailAlreadyUsed));
            }
            else if(errorCode == 'auth/invalid-email'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.InvalidEmail));
            }
            else if(errorCode == 'auth/operation-not-allowed'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.OperationNotAllowed));
            }
            else if(errorCode == 'auth/weak-password'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.WeakPassword));
            }
            else{
              reject(Error(Enum.Authentication.CreateUserErrorCode.Unknown));
            }
        });

      });
    }


    return {

      // Public methods and variables
      createUserAsync: function(email, password){
          return privateCreateUserAsync(email, password);
        }

    };
  };

  return {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function(firebaseAuthService) {

      if ( !instance ) {
        instance = init(firebaseAuthService);
      }

      return instance;
    }
  };
})();

所以我创建了一个authenticationTest.js:

var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var firebase = require('firebase');

var authenticationLib = require('../app/public/scripts/authentication');

describe("Authentication", function(){

  before(function(){

    // dev firebase 3
    var config = {
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxx",
        databaseURL: "xxxxxxxxxxxxxxxxxxxxxx",
        storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxx",
    };

    firebase.initializeApp(config);
    var firebaseAuthService = firebase.auth();
    console.log(authenticationLib);
    authenticationLib.getInstance(firebaseAuthService);
  });

  describe("Create User", function(){
    it("should be return a rejected promise with EmailAlreadyUsed error", function(){

      authenticationLib.getInstance().createUserAsync('hfdzjfezzpf@fezkfjezofez.fr', 'dhkofefzefs456fefz45').should.be.fulfilled;

    });
  });
});

但是当我启动“npm test”时,我有以下内容:

1) Authentication "before all" hook:
 TypeError: authenticationLib.getInstance is not a function
  at Context.<anonymous> (test\authenticationTest.js:24:23)

谁能解释一下我做错了什么?

非常感谢。

迈克。

最佳答案

由于您没有发布整个 js 文件,我只能给您这些提示。

  • 检查../app/public/scripts/authentication是否是正确的路径
  • 确保您导出了身份验证模块,这在您的代码中尤其不可见,并且必须完成,因为您在测试中明确要求它

编辑:似乎您缺少导出

您应该导出它,而不是返回对象。

module.export = {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function(firebaseAuthService) {

      if ( !instance ) {
        instance = init(firebaseAuthService);
      }

      return instance;
    }
 }

关于javascript - 如何使用 Mocha 测试 Javascript Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128053/

相关文章:

javascript - 从 js 对象打印 Biórn 而不是 Biórn

javascript - 来自 DynamoDB Documentclient 的模拟 promise

javascript - 什么时候调用 document.appendChild()?

java - SQLite Handler 类作为单例?

typescript - 异步/等待清晰度,以 sleep 为例

javascript - 在 JavaScript/jQuery 中使用 Canvas 显示图像

java - 如何从另一个类的数组中打印特定行

java - 没有 final 修饰符,Initialization On Demand Holder 成语线程安全吗

angularjs - 使用 Node.js、Gulp.js 和 Mocha 对 AngularJS Controller 进行单元测试

node.js - 如何在 IntelliJ IDEA 13(或 WebStorm)上远程运行 mocha 测试?