Answer the question
In order to leave comments, you need to log in
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)
});
});
Answer the question
In order to leave comments, you need to log in
var object = function(){new Checkbox();};
assert.throws(object)
var Construct = function(a, b) {
var error = {};
error.message = "wrong params";
if (true) { return error }; //делаете тут проверку
// а тут дальше пишите ваш "конструктор"
};
var a = new Construct(); // Object {message: "wrong params"}
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.
function Checkbox(elementId, target, expression) {
if(arguments.length < 3) {
throw new Error('Не переданы обязательные аргументы!');
}
// Ваш код
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question