john
john

Reputation: 11

how to test private function using mocha?

As i am new to unit testing , I want to test my javascript code its very confusing .. i really want some ones help who could tell the solution for my problem .??

if (!Notification) {
 Notification = {};
  else {
    if (typeof Notification != "object") {
      throw new Error(" already exists ");
    }
  }
 Notification.admin = function() {
    var res = {};
    var prevent = "";

    var DefaultValue = function(ans, type, commnon, status) {
      var notify = type.concat(common);
      if ($("#method").val() == "false" && type == "Text") {
        if (status) {
          return data = '<label class="checkbox-label"><input data-role="ux-checkbox" type="checkbox" disabled="disabled" data-type="' + notify + '" class="grid-checkbox">&nbsp;&nbsp</label>';
        } else {
          return data = '<label class="checkbox-label">' + '<span class="no-checkbox-label" >' + "-" + '</span>' + '</label>';
        }
      } else if (status) {
        if (ans) {
          return data = '<label class="checkbox-label"><input data-role="ux-checkbox" checked=checked type="checkbox" data-type="' + notify + '" class="grid-checkbox ">&nbsp;&nbsp</label>';
        } else {
          return data = '<label class="checkbox-label"><input data-role="ux-checkbox" type="checkbox" data-type="' + notify + '" class="grid-checkbox">&nbsp;&nbsp</label>';
        }
      } else {
        return data = '<label class="checkbox-label">' + '<span class="no-checkbox-label" >' + "-" + '</span>' + '</label>';
      }
    };
    this.init = function() {


    };}; Notification.Obj = new Notification.admin();

  $(document).ready(function() {

Notification.Obj.init();

  });

This is my private function which i want to unit test as i am using mocha and chai ..

i am not able to unit test this function

Upvotes: 1

Views: 1502

Answers (1)

k0pernikus
k0pernikus

Reputation: 66589

You don't write tests for private methods.

Public methods are the public interface of a class. The ones that are called from the outside. Private methods are implementation details that you don't care about.

The scope of a unit test is to the test all the public methods of a class. (And no, making private methods public within the class is not the solution for that.)

Refactor the actual business part of your private method out into a new service. That service will have the functionality provided through a public method. You can test that service. In you current service you can then inject that service and use its functionality.

That being said: You can only unit test method that don't have side-effects and whose dependency you can mock away (dependency injection).

Upvotes: 3

Related Questions