A
A
Alexey2016-07-06 08:27:33
JavaScript
Alexey, 2016-07-06 08:27:33

How to handle and test the missing required constructor arguments error when creating an object?

How can you prevent the constructor from creating an instance if the required arguments are not passed (respectively, these required arguments must be designated) and check all this with a test.
Correct option, as per the solution suggested by @mudrenokanton

// код
"use strict";
var Checkbox = function(elementId,target,expression){
    if(elementId == undefined || target == undefined || expression == undefined){
        return {error:true}
    }
    // ...
};
// тест
describe("simple create class object Checkbox", function () {
    it("should throw exception with no arguments", function () {
        var object = new Checkbox();
        assert(object.error)
    });
});

https://jsfiddle.net/Quncore/hxzycx5y/

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Mudrenok, 2016-07-06
@Qwal

var object = function(){new Checkbox();};
assert.throws(object)

What's going on here? You pass the body of the function to the assert, you don't call anything and you don't compare it to anything.
If you want to prevent an action, then write in a try catch block.
For good, it's better to create a factory object, and then call initialize(...params) for it, in which to do the necessary check. Why do you need this imitation of the work of designers.
upd. And you should also understand that there are no constructors, it's just a function call in which you can do whatever you want:
var Construct = function(a, b) { 
    var error = {}; 
    error.message = "wrong params"; 
    if (true) { return error }; //делаете тут проверку
    // а тут дальше пишите ваш "конструктор"
};
var a = new Construct();  // Object {message: "wrong params"}

S
Stanislav Makarov, 2016-07-06
@Nipheris

Eh, what people don't do to fix JS.
The best way to test for missing required arguments error is to use TypeScript.
As for your option - I would do a strict check for undefined, tk. null can sometimes be passed as an argument value - then your check will not work correctly.

D
Dmitry Belyaev, 2016-07-06
@bingo347

function Checkbox(elementId, target, expression) {
  if(arguments.length < 3) {
    throw new Error('Не переданы обязательные аргументы!');
  }
  // Ваш код
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question