I'm new to JS testing and I would like to understand how to test a JS function I have. I'm using Teaspoon-mocha as the testing library and the function I would like to test is:
var C_FORM = "http://www.exmple.com/SomeForm#Form";
function getNamespace(uri) {
var parts = uri.split("#");
if (parts.length == 2) {
return parts[0];
} else {
return "";
}
}
I would like to have an example how to test this specific function.
This function actually getNamespace from the final part of a specific URI which is defined by that var C_FORM so the result is that is getting the namespace which is Form.
I would like to test this function if it is doing this by Teaspoon but as above I'm not familiar with this kind of testing, I need just an example to get familiar.
I tried the next solution but I get that equal is undefined:
describe("Application", function() {
it("Gets Namespace", function() {
var uri = "http://www.test.com/SomeTest#Test";
expect(getNamespace(uri).to.equal("http://www.test.com/SomeTest"))
})
});
Please try this way:
expect(getNamespace(uri)).to.equal("http://www.test.com/SomeTest")
Related
Hello.
2 weeks ago I started to study Node.
I decided to implement my server built on MVC as the training.
I used to do it with PHP.
I can not implement a function call, the name of which is calculated by the program.
File router.js
var maincontroller = require("../controllers/maincontroller");
var storecontroller = require("../controllers/storecontroller");
var additionalcontroller = require("../controllers/additionalcontroller");
module.exports = {
findMainRoute: function (globalarray) {
... code
var nameOfController = temparray[0];
var nameOfFunction = temparray[1];
// var execFunction = nameOfController + '.' + nameOfFunction +'(globalarray);';
// eval(execFunction);
... code
}
}
In the file, the program calculates the name of the controller and the name of the function that the router needs to run. In the commented lines, calls this function with EVAL. This method works, but does not suit me.
At the moment when it works, one of the controllers will be called.
Controller maincontroller.js
module.exports = {
processingMain: function (globalarray) {
... code
globalarray.readFile = globalarray.mainDirectory + '/app/views/0000_main.html';
globalarray.contentType = 'text/html';
... code
}
}
If the call were not dynamic, I would write a call to the controller like this:
maincontroller.processingMain(globalarray);
Which JS / Node code should I write to replace eval with the PHP function analogue call_user_func_array?
For 3 days I tried 100 variants of applications Apply, Call, New Function. It seems that my knowledge of Js is too weak for such a task.
Technically you can always execute a method of an object via string:
let basicObject = {
method: () => console.log('method was executed')
}
let methodName = 'method';
basicObject[methodName](); //prints "method was executed"
Maybe you can integrate that somewhere.
I have a javascript function like this
function formatInput(input) {
//want to test only this immediate statement
var type = input.ipType.toString().toLowerCase().trim();
var afterVormat = someFunction(type);
return afterFormat;
}
I am able to test this function(value of afterFormat) correctly , but is it possible/how to test a specific line in function since I am not returning type.
For example I want to test if var type is as it is expected
Is it possible/how to test a specific line in function?
The immediate answer: no.
The solution
One of the outcomes of adhering to TDD is that it forces you to build code in isolated, testable blocks. This is a direct consequence of the fact that you cannot perform test(s) of the individual lines of a function. In your case the solution is to restructure your code to:
var type = function(){
return input.ipType.toString().toLowercase().trim();
};
function formatInput(input) {
var type2 = type();
var afterVormat = someFunction(type);
return afterFormat;
}
Now you have made type an isolated block that you can test.
If you combine this with use of Sinon.JS you can use a spy to test that an invocation of function formatInput() will also result in the invocation of type() and thereby you know for sure that var type2 has been assigned the intended value.
I’m not aware of any specific and more advanced unit testing method/system for javascript, but you can have a simple assertion function to test individual lines of code for debugging purpose like this:
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
(Code taken from TJ Crowder's answer to another question.)
Then you can just use it to check for instance the var type like this:
assert(type == "something expected here and shall throw an error otherwise");
You can use console.log() function for that. As below.
function formatInput(input) {
var type = input.ipType.toString().toLowerCase().trim();
console.log(type);
var afterVormat = someFunction(type);
return afterFormat;
}
Also you can use debugger; also, to debug the code line by line.
function formatInput(input) {
var type = input.ipType.toString().toLowerCase().trim();
debugger;
var afterVormat = someFunction(type);
return afterFormat;
}
and just press F10 key to debug the code and you can check the values in console.
I see some javascript and try to implement the function seperated to reuse it.
This is the old code:
var ListRenderRenderWrapper = function(itemRenderResult, inCtx, tpl)
{
var iStr = [];
iStr.push('<li>');
iStr.push(itemRenderResult);
iStr.push('</li>');
return iStr.join('');
}
And I would like to make something like this:
function wrapItems(itemRenderResult, inCtx, tpl)
{
var iStr = [];
iStr.push('<li>');
iStr.push(itemRenderResult);
iStr.push('</li>');
return iStr.join('');
}
var ListRenderRenderWrapper = wrapItems(itemRenderResult, inCtx, tpl);
is this ok or do I need to do it in another way?
If you just want to assign that function to a new variable so you can call it with a different name, simply do:
var ListRenderRenderWrapper = wrapItems;
The confusion may be coming from the fact that in JavaScript a function can be stored inside a variable and called as a function later.
This means that:
function thing() { /* code */ }
is the same as:
var thing = function() { /* code */ }
(Aside: I know there are subtle differences with hoisting etc, but for the purposes of this example they are the same).
I have created this:
var where = function(){
sym.getSymbol("Man").getPosition()
}
console.log(where);
if (where()<=0){
var playMan = sym.getSymbol("Man").play();
} else {
var playMan = sym.getSymbol("Man").playReverse();
}
This is for Edge Animate hence all the syms. I am trying to access the timeline of symbol Man, then if it is at 0 play it. But it isnt working and the reason, I think, is that I have an incomplete understanding of how a var works. In my mind I am giving the variable 'where' the value of the timeline position of symbol 'Man'. In reality the console is just telling me I have a function there, not the value of the answer. I have run into this before and feel if I can crack it I will be a much better human being.
So if anyone can explain in baby-language what I am misunderstanding I would be grateful.
Thanks
S
var where = function () { ... };
and
function where() { ... }
are essentially synonymous here. So, where is a function. You are calling that function here:
if (where()<=0)
However, the function does not return anything. You need to return the value from it, not just call sym.getSymbol("Man").getPosition() inside it.
That, or don't make it a function:
var where = sym.getSymbol("Man").getPosition();
if (where <= 0) ...
The value will only be checked and assigned once in this case, instead of updated every time you call where().
Try
var where = function()
{
return sym.getSymbol("Man").getPosition();
};
Your code wasn't returning anything.
var where = function() {
return sym.getSymbol("Man").getPosition()
}
console.log(where);
if(where()<=0) {
var playMan = sym.getSymbol("Man").play();
} else {
var playMan = sym.getSymbol("Man").playReverse();
}
I am messing with Javascript code that needs to have variable dynamic part.
I am trying to substitute this piece of Javascript code:
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
with something like:
var encapsulatedData = "var data = document.getElementById('IDofSomeHiddenField').value;";
var encapsulatedPrint = "var print = document.getElementById('IDofOutputField');";
so that when I use somewhere in Javascript code:
encapsulatedData;
encapsulatedPrint;
this will work:
print.value = data;
But it does not work.
Is there a way how to declare:
var encapsulatedData
var encapsulatedPrint
in similar manner like I wrote above, so that:
print.value = data;
works?
Do you mean magically create global variables?
function encapsulatedData() {
window.data = document.getElementById('IDofSomeHiddenField').value;
}
function encapsulatedPrint() {
window.print = document.getElementById('IDofOutputField');
}
encapsulatedData();
encapsulatedPrint();
print.value = data;
This is not very sanitary code, and what you want is probably not what you should be doing. Could you step back and say what your goal is, rather than the means to that goal? I suspect what you really want to be using are closures or returning first-class functions for delayed evaluation.
For example:
function makePrinter(id) {
var outputfield = document.getElementById(id);
return function(value) {
outputfield.value = value;
}
}
function getValue(id) {
return document.getElementById('IDofSomeHiddenField').value;
}
var data = getValue('IDofOutputField');
var print = makePrinter('IDofOutputField');
print(data);
You have a syntax error I think. You're not closing the parentheses on the first and second lines.
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
It is also bad form to use JS evaluation like you're attempting to do. If anything you really want to create a function for each of the page elements that returns the page element. ECMAScript 5 has properties which I think is sort of what you're looking for with what you're trying to do but that isn't how ECMAScript 3 JS can work.