I'm using Qunit and Date.js to test some API functions that I wrote. Here's my code:
asyncTest("createDeal", 4, function () {
var okStartDate = Date.today().addDays(4),
notOkStartDatePast = Date.today().addDays(-1),
notOkStartDateFuture = Date.today().addDays(1),
okEndDate,
notOkEndDateForOkStartDate;
okEndDate = okStartDate.addDays(8);
notOkEndDateForOkStartDate = okStartDate.addDays(1);
$.post(createApiUrl("deal/create/1"), {"start_date" : okStartDate, "end_date" : notOkEndDateForOkStartDate}, function(data) {
equal(data, '{"result":"fail"}', "The expected error was thrown");
});
$.post(createApiUrl("deal/create/1"), {"start_date" : notOkStartDatePast, "end_date" : okEndDate }, function(data) {
equal(data, '{"result" : "fail"}', "The expected error was thrown");
});
$.post(createApiUrl("deal/create/1"), {"start_date" : notOkStartDateFuture, "end_date" : okEndDate }, function(data) {
equal(data, '{"result" : "fail"}', "The expected error was thrown");
});
$.post(createApiUrl("deal/create/1"), {"start_date" : okStartDate, "end_date" : okEndDate }, function(data) {
equal(data, '{"result" : "success"}', "Params passed in were OK. Query ran OK.");
start();
});
});
Qunit keeps crashing on the first test, telling me:
TypeError: Object [object DOMWindow] has no method 'getTime'
And throws out the entire function in the asyncTest. Am I doing something wrong, or is this a bug in Qunit or Date.js?
Using Date objects or passing them around is something that JS (or maybe Date?, don't know really) doesn't seem to like. I changed my function call to:
$.post(createApiUrl("deal/create/1"), {"start_date" : notOkStartDatePast.toISOString(), "end_date" : okEndDate.toISOString() }, function(data) {
equal(data, '{"result" : "fail"}', "The expected error was thrown");
});
I am going to leave the question open for some time in case anyone wants to explain why this works while my original code doesn't.
Related
I am using this code for sending ajax request but it is showing 400 Bad request error. anyone please tell me the error in this. i am totally stucked.
Thanks.
function bulk_setup_post_type()
{
wp_enqueue_style( 'customstyle', plugins_url( 'admin/css/custom.css' , __FILE__ ) );
wp_enqueue_script( 'customjs', plugins_url( 'admin/js/custom.js' , __FILE__ ) );
wp_localize_script('customjs', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_register_scripts', 'bulk_setup_post_type');
add_action('wp_ajax_extract_upload_data', 'extract_upload_data');
add_action('wp_ajax_nopriv_extract_upload_data', 'extract_upload_data');
function abc(file){
if(file!='')
{
jQuery.ajax({
url : ajax_object.ajax_url,
type : 'POST',
data : {
action : 'extract_upload_data',
path : file,
},
success : function( response ) {
//console.log(response);
alert(response);
}
});
}
else{ alert('File ' + file + 'not found.');}
}
I believe your URL contains no domain name
I'm using jasmine values to get some useful information for the it results.
const resultLeaker = {
suiteStarted: function(result) { jasmine.results = {suite: result}; },
specStarted: function(result) { jasmine.results.spec = result; }
};
jasmine.getEnv().addReporter(resultLeaker);
const reporters = require('jasmine-reporters');
const junitReporter = new reporters.JUnitXmlReporter({
savePath: 'testresults',
consolidateAll: false,
filePrefix: 'xmloutput'
});
jasmine.getEnv().addReporter(junitReporter);
The above code has a problem with "results", VB code refers that "[ts] Property 'results' does not exist on type 'typeof jasmine'.
Without results, this code doesn´t works.
At the project build i have the expected error:
Build:Property 'results' does not exist on type 'typeof jasmine'
I have to get free of this error, how can i do this?
Do you have and idea?
With jasmine, when I try to test the property of an object :
var foo = {property1:'123'}
it('foo.property1 should be 123'', function() {
expect(foo.property1).toEqual("123");
});
it('bar.property2 should be 456', function() {
expect(bar.property2).toEqual("456");
});
If this object is undefined, I get the error :
TypeError: Cannot read property 'property2' of undefined
and it breaks ALL my spec.
To solve the problem I use a conditional to test if bar exists in the first place :
var foo = {property1:'123'}
it('foo.property1 should be 123'', function() {
expect(foo.property1).toEqual("123");
});
it('bar.property2 should be 456', function() {
if(!bar){
fail("bar does not exist");
}else{
expect(bar.property2).toEqual("456");
}
});
Is there a better and more elegant way ?
I have a problem in "Ajax Loader image". On Firefox it is working fine but on chrome that ajax loader image does not seems.
I have a some attributes on sidebar when I check any attribute Products changes according with it and a Preloader image generated before ajax completed.What I am doing is when I check on any attribute first I insert a gif image in div html and show it using .show() method and after success of ajax I set div html null and hide it.
You can see that div in firebug (<div id="ajax_loader_div" style="display:none;"></div>)
Code is really complicated that's why I am not posting code here.Really very Sorry for that.You can see it on http://vcompare4u.com/wpcompare/products/laptops/
I need help.Please
Thanks!!!
I've seen your code
It is well known a synchronous requests will lock the UI. So not surprisingly on chrome and safari, (it does in Firefox interestingly)
can you try something like this
jQuery('#customtag_widget-2 .compare_attribute').bind('change',
jQuery.filterProductsCompare2 = function () {
$.ajaxSetup({async:false});
jQuery('#ajax_loader_div').css('display', 'block');
jQuery('#ajax_loader_div').html('<img src="http://vcompare4u.com/wpcompare/wp-content/themes/compare/_assets/img/ajax-loader.gif" / >');
jQuery('#customtag_widget-2 .compare_attribute_group').each(function () {
jQuery(this).children().each(function () {
if (jQuery(this).children('.compare_attribute').attr('checked')) {
if (jQuery(this).children('.compare_attribute').attr('name').indexOf('b[') != -1) {
brands.push(jQuery(this).children('.compare_attribute').attr('value'));
}
if (jQuery(this).children('.compare_attribute').attr('name').indexOf('c[') != -1) {
categories.push(jQuery(this).children('.compare_attribute').attr('value'));
}
}
})
} else {
minmaxarr = jQuery(this).attr('value').split(';');
minPrice = minmaxarr[0];
maxPrice = minmaxarr[1];
}
if (!jQuery.support.placeholder) {
if (isEmptyPlaceholder == 1) {
jQuery(this).val('Search...');
}
}
})
if (jQuery('#dont_change_price').is(':checked')) {
minPrice = jQuery('#overall_min').val();
maxPrice = jQuery('#overall_max').val();
} else {}
jQuery.ajax({
url : file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
dont_change_price : dont_change_price,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (data) {
// Do stuff here
}
});
jQuery.ajax({
url : bracket_file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (bracket_data) {
// DO stuff here
}
});
if (!jQuery('#dont_change_price').is(':checked')) {
jQuery.ajax({
url : price_file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (price_data) {
// DO stuff here
}
});
}
jQuery('#ajax_loader_div').hide();
jQuery('#ajax_loader_div').html('');
$.ajaxSetup({async:true});
});
What I am trying to do is to do synchronous request for each ajax request and instead of using success functions I am using ajax request separately. Due to synchronous nature each request will be processed one after another.
Inspecting your code in chrome console I've seen ajax loader for very little moment get hided immediately.
here is reference problem same like yours
Force UI repaint in Webkit (Safari & Chrome) right before Synchronous "Ajax" request
<div id="#ajax_loader_css" style="display:none;"></div>
should be
<div id="ajax_loader_css" style="display:none;"></div>
Based on the accepted answer here valid values for an id element are
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Firefox is obviously trying to fix it by removing the invalid character making the #ajax_loader_css css selector match something where as chrome is ignoring it so your selector matches nothing.
I have an AJAX call to check the availability of username using Dojo and PHP. Everything is working great, but there is something huge happening behind. Every time I type a word or during onBlur event, dojo makes AJAX call twice and sometimes thrice. I read this link and they say it is fixed since v1.3, I am using v1.7. I tried putting the AJAX function inside setTimeout() and put a 3 secs delay but still the same thing happens. How can prevent that and do only one AJAX call?
var _username = new dijit.form.ValidationTextBox({
name : "{{ username.name }}",
type : "text",
required : true,
invalidMessage : message.invalid.username
}, "{{ username.id }}");
dijit.byId("{{ username.id }}").validator = fnUsernameAvailable;
function fnUsernameAvailable(a) {
if (a === "" )
return false;
dojo.xhrPost({
url : "{{ site_url() }}/ajax/check_username_availability",
handleAs: "json",
content : {
username : a,
csrf_libtracking : fnCsrf()
},
load : function(data) {
_isAvailable = data.result;
}
});
return _isAvailable;
}
You could use a little trick like :
inside you ValidationTextBox, add a property :
var _username = new dijit.form.ValidationTextBox({
_beingChecked: false,
name : "{{ username.name }}",
type : "text",
required : true,
invalidMessage : message.invalid.username
}, "{{ username.id }}");
function fnUsernameAvailable(a) {
if (a === "" || this._beingChecked)
return false;
this._beingChecked = true;
dojo.xhrPost({
url : "{{ site_url() }}/ajax/check_username_availability",
handleAs: "json",
content : {
username : a,
csrf_libtracking : fnCsrf()
},
load : dojo.hitch(this, function(data) {
// _isAvailable = data.result; <-- is this really useful ?
this._beingChecked = false;
dojo.publish("some/topic/to/tell/widgets/it/is/done", [data.result]);
})
});
}
then somewhere in your code, or in your widget you dojo.subscribe to the topic, so that when something is published, you run a function ?
Thanks for the reply. My original plan was to contact the server, check if username is available, via AJAX, and return the var _isAvailable to trigger the invalidMessage property of the ValidationTextBox if the result is false. This would also trigger the tooltip to appear beside the textbox which I wanted to happen.
Pardon for my little knowledge on dojo as this is my first time using this framework.