I am working on jasmine tests for a button on rails which changes html dir attribute. My click functionality is working fine but when I run my tests, I do see reference error. Any help or suggestions would be highly appreciated.
view.html.erb
<p><%= button_tag 'Convert', remote: 'true' %></p>
convert.js
$(document).ready(function(){
$('button').on('click', function (){
$('html').attr('dir', getElement);
});
function getElement() {
return this.getAttribute('dir') === 'rtl' ? 'ltr' : 'rtl';
}
});
Here is my jasmine test file.
conversion_spec.js
//= require jquery
describe('#rtl', function (){
describe("Testing spies", function () {
it("Should replace the return value of function being spied on", function () {
// Arrange
var myApp = new getElement();
spyOn(myApp, "getAttribute").and.returnValue('rtl');
// Act
var result = myApp.useFlagForSomething();
// Assert
expect(result).toBe("rtl");
});
});
});
Here is my error message:
Failures:
#rtl Testing spies Should replace the return value of function being spied on
ReferenceError: Can't find variable: getElement in http://localhost:45463/__spec__/conversion_spec.js (line 28)
ReferenceError: Can't find variable: getElement
at http://localhost:45463/__spec__/conversion_spec.js:28
at attemptSync (http://localhost:45463/__jasmine__/jasmine.js:1789)
at http://localhost:45463/__jasmine__/jasmine.js:1777
at http://localhost:45463/__jasmine__/jasmine.js:1762
at http://localhost:45463/__jasmine__/jasmine.js:627
at http://localhost:45463/__jasmine__/jasmine.js:357
1 spec, 1 failure
Related
Hello I am testing my code in jquery with Karma jasmine and the following code works correctly:
it("Test click", function(){
var $element = $('a#buttonID');
var spy = spyOnEvent($element, 'click');
$element.click();
expect(spy).toHaveBeenTriggered();
});
But when I run the following code with a function inside click it doesn't work.
it("Test click", function(){
var $element = $('a#buttonID');
var spy = spyOnEvent($element, 'click');
$element.click(function(){
console.log("Execute some code here")
});
expect(spy).toHaveBeenTriggered();
});
Test click FAILED
Expected event click to have been triggered on [object Object]
The code inside the click function is not executed. I don't know if it is a timeout or is it asynchronous issue?
I have a problem I want to test this javascript
$("#ShootBtn").on('click', () => foo.testFunc());
var foo = {
testFunc: function() {
hub.server.shoot(true, username, gameCode);
}
}
I'm using Jasmine as my test framework, and I have tried Karma and Chutzpah as my test runner.
In my test project where I try to refer to the file above I try have tried a lot of different things, but I can't seem to get my head around it. The test looks like this atm.
/// <reference path="../../TankWebApplication/Scripts/jquery-3.3.1.js"/>
/// <reference path="../../TankWebApplication/Scripts/virtualjoystick.js"/>
/// <reference path="../../TankWebApplication/Scripts/gameController.js"/>
describe("DefaultTest",
function () {
beforeEach(function() {
})
it("Test",
function() {
spyOn(foo, 'testFunc');
document.getElementById('ShootBtn').click();
expect(foo.testFunc).toHaveBeenCalled();
});
});
The testFunc haven't been called says:
TypeError: Cannot read property 'click' of null
Which I think means that it cannot click on my shootBtn
Is it impossible to test this, or what do I do wrong?
What you can do is to spy on document.getElementById and make it return an object that has click function :
spyOn(document, "getElementById").andCallFake(() => ({
click: () => foo.testFunc()
}));
jsFiddle
Otherwise, create an element with id = ShootBtn, attach a click handler to it then add it to the body (all this should be done inside your test)
jsFiddle
My objective is to perform Auto-Complete feature of the same context in multiple pages/Views, for same input having the same class name (i.e. Client Name to be auto complete for many pages like Create and Edit View and others).
Since I need to call the jquery's autocomplete() in each page, I had written in
Views\Shared_Layout.cshtml
page of my project so the auto complete feature will available where required. The code I had written in _Layout.cshtml is as follows:
<script>
$(document).ready(function () {
//common
$('.form-control.salescode').autocomplete({
minLength: 4,
source: '#Url.Action("GetAccountManager", "AccountManager")',
select: callBackSalesCodeLookUp
});
});
</script>
Then any View (Create or Edit) which requires, the auto-complete feature have this code called:
<script>
function callBackSalesCodeLookUp(event, ui)
{
event.preventDefault();
var selectedArr = ui.item.value.split("|");
var accountManagerID = selectedArr[0];
var accountManagerName = selectedArr[1];
$('.form-control.salescode').val(accountManagerID);
}
</script>
However, when I ran the project, I am getting an error for pages which have not having the following code, which is as expected:
function callBackSalesCodeLookUp(event, ui)
{
event.preventDefault();
var selectedArr = ui.item.value.split("|");
var accountManagerID = selectedArr[0];
var accountManagerName = selectedArr[1];
$('.form-control.salescode').val(accountManagerID);
}
The error I am getting, is in Chrome as :
jquery-3.1.1.js:3855 Uncaught ReferenceError: callBackSalesCodeLookUp
is not defined
at HTMLDocument. (Login?ReturnUrl=%2FAccountOpeningRegister%2FCreate:393)
at mightThrow (jquery-3.1.1.js:3570)
at process (jquery-3.1.1.js:3638)
I want to less the code, and which is the reason I made up something like this. I will be glad to know if there is any better way of coding this.
Thank You
Check if the function exists in the window before calling it.
<script>
if (typeof callBackSalesCodeLookUp == 'function') {
$(document).ready(function () {
//common
$('.form-control.salescode').autocomplete({
minLength: 4,
source: '#Url.Action("GetAccountManager", "AccountManager")',
select: callBackSalesCodeLookUp
});
});
}
</script>
The following is in foo.js
var analytics = {};
analytics.myLinks = function(){
return 2;
};
analytics.myView = function() {
analytics.myLinks();
};
$('#marquee').on('click', analytics.myView);
The following is my spec file foo.spec.js Fixture is appended using jasmine-fixture utility's affix helper. (https://github.com/searls/jasmine-fixture)
(function() {
describe('click event handlers', function() {
it('calls function when #marquee is clicked on', function() {
affix('#marquee');
spyOn(analytics, 'myView').and.callThrough();
$('#marquee').trigger('click');
expect(analytics.myView).toHaveBeenCalled();
});
it('calls inner function when #marquee is clicked on', function() {
affix('#marquee');
spyOn(analytics, 'myLinks').and.callThrough();
$('#marquee').trigger('click');
expect(analytics.myLinks).toHaveBeenCalled();
});
});
}).call(this);
I am using Karma as my test runner and it throws an error on the above unit test saying
"Expected spy myView to have been called."
and
"Expected spy myLinks to have been called."
I have tried different variations of the same but not sure where I am going wrong. Please help!
i'm debugging a drupal module, the second line drupal_add_js call a js function in uc_discounts.js
drupal_add_js(drupal_get_path('module', 'uc_discounts') . '/uc_discounts.js');
drupal_add_js('(function($){jQuery(document).ready(function () { uc_discountsOnLoad(e); })})(jQuery);', array('type' => 'inline', 'group' => JS_DEFAULT, 'scope' => 'footer'));
there is an error message in firebug, ReferenceError: uc_discountsOnLoad is not defined, anyone can figure out the problems?
** update **
i knew the problems!
the uc_discountsOnLoad if defined outside (function ($) {})(jQuery); can be called~ but it can't use jquery symbol, it is a conflict!
but in the situation , how do i call this function?
function uc_discountsOnLoad(e) {
context = $('body');
uc_discountsProcessCodes(context, e);
//Add click event listener to discounts pane button once
$("input[id*=uc-discounts-button]:not(.uc_discountsOnLoad-processed)",
context).addClass("uc_discountsOnLoad-processed").click(function(e) {
uc_discountsProcessCodes(context, e);
//Return false to prevent default actions and propogation
return false;
});
}
if define the uc_discountsOnLoad(e) outside the (function ($) {})(jQuery);, $('body') will got an error!
The uc_discountsOnLoad(e) function cannot be found.
Check uc_discounts.js to see if the function actually exists.
uc_discounts.js gets loaded after the function is called? (Check your page source)