Romain
Romain

Reputation: 2348

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!

Upvotes: 0

Views: 354

Answers (1)

Andrew D.
Andrew D.

Reputation: 8220

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);

Upvotes: 0

Related Questions