Problems when testing (whilst using javascript & QUnit) - javascript

Given the following code, I have managed to write a test by making use of QUnit for the first part but was unable to test finder.doRoutefinding. How can I 'mock'the function finder.doRoutefinding? (Mockjax cannot be used here since no ajax calls are involved)
`finder.doSelectDestination = function(address)
{
finder.destination = address;
finder.doRoutefinding(
finder.departure,
finder.destination,
finder.whenRouteLoaded,
finder.showRoute);
}
test('Destination Selector',
function()
{
address="London";
finder.doSelectDestination(address);
equal(pathfinder.destination,address, "Succesful Destination Selection");
}
);

There are caveats, but you could simply replace the function with your mock:
var originalDoRoutefinding = finder.doRoutefinding;
finder.doRoutefinding = function() {
// Mock code here.
};
// Test code here.
finder.doRoutefinding = originalDoRoutefinding;
If that kind of thing works for you, you might consider using a library like Sinon.JS.

Related

obfuscate js using cli

I use javascript-obfuscator package, it works fine if I do operations with files, like:
javascript-obfuscator source.js
but I need to dynamically change js source content and get output on console in way like
javascript-obfuscator "var foo = 'bar'; alert(foo);"
Any suggestion how can I get rid from saving content to file and do it like in snippet above?
Not really considering why you'd need to do this, it looks like you'll need to use the programmatic API as described in the library's README.
Let's call this obfuscate.js:
var JavaScriptObfuscator = require('javascript-obfuscator');
var obfuscationResult = JavaScriptObfuscator.obfuscate(
process.argv[2],
{
compact: false,
controlFlowFlattening: true
}
);
console.log(obfuscationResult.getObfuscatedCode());
$ node obfuscate.js 'console.log(1)'
will then output (for example)
var _0x2b5a = ['log'];
(function (_0x630038, _0x2944a9) {
var _0x83df37 = function (_0x2ef1a5) {
while (--_0x2ef1a5) {
_0x630038['push'](_0x630038['shift']());
}
};
_0x83df37(++_0x2944a9);
}(_0x2b5a, 0xd7));
var _0x493b = function (_0x2b48eb, _0x33884a) {
_0x2b48eb = _0x2b48eb - 0x0;
var _0x41338b = _0x2b5a[_0x2b48eb];
return _0x41338b;
};
console[_0x493b('0x0')](0x1);

JavaScript - testing implementation of NodeJS readline.createInterface using Jasmine

I'm building a command-line application in NodeJS and I want to thoroughly test it using Jasmine.
I've implemented a promptUser() method which uses Node's readline.createInterface method to pose a question and pipe the response into a callback. I want to test that, given a user response of 'q', my module's quit() function is called.
However I'm struggling to test this. I don't really want to test the readline method directly, since I didn't write that code, but I reasoned that if I can create a listener on process.stdout.write then when enter command: is printed to the screen I can respond with process.stdin.write("q\n") and trigger the if/else logic.
I've simplified the code, but should explain what I'm trying to do:
Module source code:
var Cli = function() {
var rl = require('readline');
var self = this;
Cli.prototype.promptUser = function() {
var inputHandler = rl.createInterface(process.stdin, process.stdout);
inputHandler.question('enter command: ', function(answer) {
if (answer === 'q') {
self.quit();
};
});
};
Cli.prototype.quit = function() {
// doSomething
};
};
module.exports = Cli;
Jasmine test:
var Cli = require('Cli');
describe('My application.', function() {
beforeEach(function() {
cli = new Cli();
spyOn(cli, 'quit');
});
describe('Cli #promptUser', function() {
it('input of lower-case q calls cli.quit()', function() {
process.stdout.once('write', function() {
process.stdin.write("q\n");
});
cli.promptUser();
expect(cli.quit).toHaveBeenCalled();
});
});
});
I'm looking to either make this approach work or find a better way to test my code. I suspect there is probably a superior/more direct approach.

firefox addon install.rdf pass data to server on update

Is there any chance to pass some data to my server through install.rdf when my Firefox add-on check server for update?
Example:
...
<em:updateURL>http://www.site.com/update.php?var=myData</em:updateURL>
...
where "myData" is saved in options.xul or in another place like simple-storage.
Yes, but it is quite nasty. The AddonManager will replace a bunch of predefined and dynamic properties in the URL:
Register a new component implementing nsIPropertyBag2 (or use an existing implementation, such as ["#mozilla.org/hash-property-bag;1"]).
Register your component in the nsICategoryManager under the "extension-update-params" category.
Since you mentioned simple-storage: restartless add-ons must also unregister their stuff when being unloaded.
There is a unit test demonstrating how this stuff works. You of course need to adapt it a bit (if alone for require("chrome").
I found one "simple solution" but I dont know if that is also good practice ...
var origLink = "http://www.site.net/update.php?var=myData";
var newsLink = "http://www.site.net/update.php?var=" + simplePref.prefs.myData;
const {Cc,Ci,Cu} = require("chrome");
var observer = {
QueryInterface: function(iid) {
if (iid.equals(Ci.nsIObserver) || iid.equals(Ci.nsISupports)) return this;
},
observe: function(subject, topic, data){
if (topic == "http-on-modify-request"){
var channel = subject.QueryInterface(Ci.nsIChannel);
if (channel.originalURI.spec == origLink) {
channel.originalURI.spec = newsLink;
}
}
}
};
var ObsService = Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
ObsService.addObserver(observer, "http-on-modify-request", false);

Return generated Typekit id in Yeoman Generator

I'm using node-typekit to create a new Typekit empty font set in my Yeoman generator for use in my project. I am able to successfully create the kit, but cannot figure out how to return the kit id value back to the Yeoman generator so I can add the necessary Typekit script tag values to my web pages. Here is the part of my index.js generator script in question:
At the top of index.js:
var kit = require('typekit');
var typekitID = '';
function setTypekitID(theid) {
typekitID = theid;
};
And the app section:
app: function () {
var token = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var split = this.domainname.split('.');
split.pop();
var localdomain = split.join('.') + '.dev';
kit.create(token, {
name: this.appname,
badge: false,
domains: [this.domainname, localdomain],
families: []
}, function (err, data) {
setTypekitID(data.kit.id);
});
}
If instead of:
setTypekitID(data.kit.id);
I use:
console.log(data.kit.id);
The correct kit ID is displayed in the console. However, I can't quite figure out how to pass the data.kit.id value in the callback back to the generator for further use. Given the current code above, it comes back as "undefined".
Any ideas? Thanks!
Without any experience with typekit, I would guess that kit.create is an asynchronous call. When you make such a call, the generator needs to know about it, so it can delay invocation of further methods until it knows your asynchronous callback has had a chance to execute.
Try doing this:
app: function () {
var done = this.async(); // this tells the generator, "hang on, yo."
// ...
kit.create(token, { /* ... */ }, function (err, data) {
setTypekitID(data.kit.id);
done(); // calling this resumes the generator.
});
}
An example of how the default generator-generator uses this can be found here.

JAWR i18n: unit testing javascript when using messages

Our application currently shares messages between the Java and Javascript side. They are stored as resource bundles in the class path, and we have a custom controller that returns all the messages as Json. The client side code look like this:
// This calls the controller to get all the messages
var messages = MessageBundle();
var text = messages.get('my.message', 1);
This is great because we can mock "messages" in our unit tests.
I want to start using JAWR for this, since we already use it for other things. The problem is JAWR generates the following Javascript object:
var text = messages.my.message(1);
This means the code cannot be unit tested anymore unless the unit tests also define a global "messages" variable with the right nested objects. Is there a way around this? Any idea how to extend JAWR to make this unit-testable?
Currently my work around is:
function messages() {
var args = Array.prototype.slice.call(arguments);
var messageId = args.shift();
var messageFunc = window.messages;
messageId.split('.').forEach(function(part) {
messageFunc = messageFunc[part];
});
return messageFunc(args);
}
// Same syntax as the old one, but uses the JAWR object behind the scenes
// This function is easy to mock for a unit test
var text = messages('my.message', 1);
Thanks for any ideas!
Maybe next samples can help you.
1)
function messagesTester(funcPath,id) {
var args=funcPath.split('.'),root=window.messages;
for(var i=0;i<args.length;i++)root=root[args[i]];
return root(id);
// or if more that one parameter for *func*, then, for example:
// return root.apply(null,Array.prototype.slice(arguments,1));
}
var text = messagesTester('my.message',1);
2)
function messagesTester(funcPath) {
var args=funcPath.split('.'),root=window.messages;
for(var i=0;i<args.length;i++)root=root[args[i]];
return root;
}
// var text = messagesTester('my.message')( /*arguments list*/ );
var text = messagesTester('my.message')(1);

Categories

Resources