Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active January 1, 2018 20:38
Show Gist options
  • Select an option

  • Save Integralist/5772010 to your computer and use it in GitHub Desktop.

Select an option

Save Integralist/5772010 to your computer and use it in GitHub Desktop.
Mocking a Window object for unit-testing purposes
function bindEvents() {
news.$(global).on('resize', handleResize);
}
function init(windowMock, newsMock) {
global = windowMock || window;
news = newsMock || newsModule;
}
var mocks = {
resizeCalled: false,
createFakeWindow: function(width, height) {
var module = this;
return {
document: {
documentElement: {
clientWidth: width,
clientHeight: height
}
},
resizeTo: function(width, height) {
this.document.documentElement = {
clientWidth: width,
clientHeight: height
};
}
};
},
fireResizeEvent: function() {
this.handler();
},
news: {
$: function(element) {
return {
on: function(event, handler) {
if (event === 'resize') {
mocks.resizeCalled = true;
}
mocks.handler = handler;
}
};
}
}
};
it('should bind to `resize` event on `init`', function(){
var fakeWindow = mocks.createFakeWindow(320, 480);
deviceInspector.init(fakeWindow, mocks.news);
expect(mocks.resizeCalled).toBeTruthy();
});
it('should only publish `device` event when device type changes', function(){
var fakeWindow = mocks.createFakeWindow(1008, 1024),
device = deviceInspector.init(fakeWindow, mocks.news);
fakeWindow.resizeTo(960, 1024);
mocks.fireResizeEvent();
fakeWindow.resizeTo(320, 480);
mocks.fireResizeEvent();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment