简体   繁体   English

如何用Mocha测试Javascript Singleton

[英]How to test with Mocha a Javascript Singleton

I'm new in Javascript, and I want to create units tests to test a Singleton. 我是Javascript的新手,我想创建单元测试来测试Singleton。

So I have the following Singleton in a authentication.js file : 所以我在authentication.js文件中有以下Singleton:

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;
    }
  };
})();

So I create a authenticationTest.js : 所以我创建了一个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;

    });
  });
});

But when I launch 'npm test', I have the following : 但是当我启动'npm test'时,我有以下内容:

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

Can anyone explain me what i'm done wrong? 谁能解释一下我做错了什么?

Thanks a lot. 非常感谢。

Mike. 麦克风。

since you did not post the whole js file i can only give you these hints. 因为你没有发布整个js文件我只能给你这些提示。

  • check if ../app/public/scripts/authentication is the correct path 检查../app/public/scripts/authentication是否是正确的路径
  • make sure you exported the authentication module, this in particular is not visible in your code and must be done because you're explicitely requiring it inside your test 确保您导出了身份验证模块,这在您的代码中是不可见的,必须完成,因为您在测试中明确要求它

edit: seems that you're missing the export 编辑:似乎你错过了导出

in place of returning the object, you should export it. 代替返回对象,您应该导出它。

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;
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM