How to mock $xhr with Jack? - javascript

I have a function like:
function Aoeu($xhr) {
$xhr('GET', '/url', function(code, response) {});
};
How do I create with Jack a $xhr mock that's to be passed into Aoeu()?
The following says that the mock is an object, not a function (which makes sense):
AoeuTest.prototype.testAoeu = function() {
jack(function() {
var xhrStub = jack.create('$xhr', ['']);
// jack.expect('$xhr');
var aoeu = new Aoeu(xhrStub);
});
};

Related

How to resolve defered in argument with Sinon?

Is it possible to get sinon to resolve an argument, when the argument is a defered object?
Consider this:
function needToTest() {
var isInitialized = q.defer();
var importantResult;
var publicStuff;
publicStuff.isInitialized = isInitialized.promise.then(function(res) {
importantResult = res;
});
var someClass = new SomeClass(isInitialized);
publicStuff.getResult = function() {
return importantResult;
};
return publicStuff;
}
I use q as promise library, but it's not important.
SomeClass looks something like this:
function SomeClass(promise) {
this.foo = function() {
//
};
//after some initializing:
var result = true; //or false
promise.resolve(result);
}
It might be that this mock should have some sort of function to resolve a promise, but this is what I have so far:
var someClassMock = sinon.stub().withArgs(q.defer());
someClass.prototype.foo = sinon.stub().returns('foo');
return someClassMock;
and ultimately I try to create a testcase using sinon and Squire like this:
describe('test', function() {
var needToTestInstance;
beforeEach(function(done) {
new Squire()
.mock('someClassMock', someClassMock)
.require(['needToTest'], function(module) {
needToTest = module;
//Need to get the needToTest().isInitialized to resolve with a value!
done();
});
});
describe('importantResult', function() {
expect(needToTestInstance.getResult()).to.be(true);
});
});
Is it possible to get isInitialized to resolve at any point in the test?

Sinon stub not working when trying to mock out an instance of an object

I am trying to mock out every instance that is created with the new keyword for an object.
Here is the Object I am trying to mock out:
var SharedWhiteboardView = function(moduleEl, domService) {
'use strict';
var self;
var sharedWhiteboardProblemImage;
var whiteboardController;
var caller = false;
var toolbarController;
return {
initWhiteboard : function()
{
self = this;
sharedWhiteboardProblemImage = domService.find(moduleEl, '#sharedWhiteboardModule-sharedWhiteboardProblemImage');
var toolbarEL = $('#sharedWhiteboard-toolbar');
toolbarController = new ToolbarController(WhiteboardConstants.SHARED_WHITEBOARD_ID, toolbarEL, null);
toolbarController.init(false);
whiteboardController = toolbarController.getWhiteboardController();
},
enableWhiteboardEdition : function(enabled)
{
if(self.getWhiteboardObject() && self.getWhiteboardObject.hasOwnProperty('enableEdition')) self.getWhiteboardObject().enableEdition(enabled);
whiteboardController.setEnabled(enabled);
}
};
}
This is the file which I am trying to test and it creates a new instance of the above object
Box.Application.addModule('SharedWhiteboardModule', function(context) {
'use strict';
var self;
var moduleEl;
var domService;
var sharedWhiteboardView;
var modal;
var assignmentTimer = 3000;
var sharing = false;
var assignmentImageData = '';
return {
/**
* Initializes the module and caches the module element
* #returns {void}
*/
init: function() {
self = this;
domService = context.getService('DomService');
moduleEl = context.getElement();
sharedWhiteboardView = new SharedWhiteboardView(moduleEl, domService);
sharedWhiteboardView.initWhiteboard();
sharedWhiteboardView.enableWhiteboardEdition(false);
};
}
I am trying to write a unit test to test that the sharedWhiteboardView.enableWhiteboardEdition method is called with 'false'
However I am failing to attach a spy or stub that method out. I have tried these solutions and they did not work
//First Attempt
sinon.stub(SharedWhiteboardView, "enableWhiteboardEdition", function() {return 0})
// Second Attempt
sinon.stub(SharedWhiteboardView.prototype, "enableWhiteboardEdition").returns(0);
//Third Attempt
sandbox.stub(SharedWhiteboardView.prototype, 'enableWhiteboardEdition', checkEnableWhiteboardEdition());
//Fourth Attempt Trying the answer provided by chrmod
it.only('when type is "SharedWhiteboardModule-setEditable" should call sharedWhiteboardView.enableWhiteboardEdition', function (done) {
const view = SharedWhiteboardView();
sinon.stub(view, "enableWhiteboardEdition", function() {
console.log('Hit');
});
module.onmessage('SharedWhiteboardModule-setEditable', true);
done();
});
No error but it does not hit the console.log, I removed the 'new' keyword as suggested
Errors that I got:
-Attempted to wrap undefined property enableWhiteboardEdition as function
-Cannot stub non-existent own property enableWhiteboardEdition
Please any help would be great. I have reached a dead end here.
Here is a codepen: http://codepen.io/anon/pen/bgmNxx?editors=0011
All I am trying to do is to have the Fake method get hit when my module calls enableEdition
SharedWhiteboardView is not a constructor, it is rather a factory function. Once called (without new) it returns new object that has enableWhiteboardEdition as own property.
Thus a stub has to be set on that object:
const view = SharedWhiteboardView();
sinon.stub(view, "enableWhiteboardEdition", function() {return 0});
This did it.
it('when type is "SharedWhiteboardModule-setEditable" should call setEditable with appropriate callback', function (done) {
var mockSharedWhiteboardView = {
enableWhiteboardEdition: function() {},
initWhiteboard: function() {},
initScrollBar: function() {},
refreshScrollBar: function() {},
isMainWhiteboardAvailable: function() {}
};
sandbox.spy(mockSharedWhiteboardView, 'enableWhiteboardEdition');
var tempGlobals = {
SharedWhiteboardView: global.SharedWhiteboardView
};
global.SharedWhiteboardView = function() {
return mockSharedWhiteboardView;
};
module = Box.Application.getModuleForTest('SharedWhiteboardModule', contextFake);
module.init();
var shouldEnable = true;
module.onmessage('SharedWhiteboardModule-setEditable', shouldEnable);
assert(mockSharedWhiteboardView.enableWhiteboardEdition.calledWithExactly(shouldEnable),
'should enable the whiteboard');
shouldEnable = false;
module.onmessage('SharedWhiteboardModule-setEditable', shouldEnable);
assert(mockSharedWhiteboardView.enableWhiteboardEdition.calledWithExactly(shouldEnable),
'should not enable the whiteboard');
// cleanup
global.SharedWhiteboardView = tempGlobals.SharedWhiteboardView;
done();
});

PubsubJs and *this* is undefined when subscribing to a message

I have the following code:
someClass1 = function () {
this.doStuff = function () {
PubSub.publish('topic1', { id: 1 });
}
}
someClass2 = function () {
this.forename = 'bob2';
PubSub.subscribe("topic1", function (msg, data) {
log(msg, data, this.forename);
});
}
function log() {
console.log(arguments);
}
var c1 = new someClass1();
var c2 = new someClass2();
c1.doStuff();
and I am using the pubsubjs library (https://github.com/federico-lox/pubsub.js)
The code is simple - publish a message and handle it in another class (someClass2) using PubSub
My question is that when I publish a message and handle it in someClass2, this is undefined. This occurs at the line: log(msg, data, this.forename);
This means I cant access any of the someClass2 properties/functions. What do I need to do to get the this to not be undefined? Is this possible? Are they other libraries that will help? Am I doing it wrong....
All help apprenticed! Thanks
You're passing an unbound function to subscribe. Such a function has "no idea" about this. You have to bind it:
PubSub.subscribe("topic1", (function (msg, data) {
log(msg, data, this.forename);
}).bind(this));
this is not what you expect inside the callback, just cache a copy of this as another variable outside:
someClass2 = function () {
this.forename = 'bob2';
var that = this;
PubSub.subscribe("topic1", function (msg, data) {
log(msg, data, that.forename);
});
}

JavaScript Object storage and usage via sessionStorage

var obj = {
conn : null,
first : function(thisIdentity) {
"use strict";
var myObj = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
myObj.conn = new Connection(data.user_id, "127.0.0.1:80");
sessionStorage.setItem('connection', JSON.stringify(myObj.conn));
}
});
},
second : function(thisIdentity) {
"use strict";
var myObj = this;
var conntn = sessionStorage.getItem('connection');
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
var parsedConnection = JSON.parse(conntn);
parsedConnection.sendMsg(data.id, data.nid);
}
});
}
};
var Connection = (function() {
function Connection(uid, url) {
this.uid = uid;
this.open = false;
this.socket = new WebSocket("ws://"+url);
this.setupConnectionEvents();
},
sendMsg : function(id, nid) {
alert("Working");
},
// other functions
})();
Now basically an object is assigned to conn variable in AJAX callback function of first function and I am storing the object via sessionStorage and retrieving the object in the second function and using it in the AJAX callback but when I call the method via parsedConnection.sendMsg(data.id, data.nid); it is throwing an error that
TypeError: parsedConnection.sendMsg is not a function
I did use console.log(parsedConnection); and it shows that object is there with proper values. I just want to know how to retrieve the object and call the method on it in AJAX callback function of second. Thanks!

Jasmine.js How to unit test a function that is calling an undefined function?

My function getLink(rel) calls a function that does not exist in the testing environment.
getLink: function(rel) {
var schemaLink = null;
var schemaLinks = this.collection.getItemSchema().links;
schemaLinks.forEach(function(link) {
if(link.rel === rel) {
schemaLink = link;
return false;
}
});
return schemaLink;
},
this.collection does not exist and I wouldn't want to test it as I want to isolate the object I am currently testing. How would I spy this function (or stub it, whatever is the thing to do, but I think it's stub) with Jasmine 2.0?
You can call your function in context of spy object using call method. It will look something like this:
describe('getLink()', function(){
var result, fooLink, barLink, fakeContext;
beforeEach(function(){
fakeContext = {
collection: jasmine.createSpyObj('collection', ['getItemSchema']);
};
fooLink = {rel: 'foo'};
barLink = {rel: 'bar'};
fakeContext.collection.getItemSchema.andReturn([fooLink, barLink]);
});
desctibe('when schemaLink exists', function(){
beforeEach(function(){
result = getLink.call(fakeContext, 'foo')
});
it('calls getItemSchame on collection', function(){
expect(fakeContext.collection.getItemSchame).toHaveBeenCalledWith();
});
it('returns fooLink', function(){
expect(result).toBe(fooLink);
});
});
desctibe('when schemaLink does not exist', function(){
...
});
});

Categories