The response time feature appears to be malfunctioning within Mockjax

How can I simulate a long response time using Mockjax? Despite setting the responseTime to 20 seconds, my ajax call is still being executed immediately when the page loads.

Any suggestions on how to fix this issue?

To isolate potential sources of error, I've minimized my test page:

<!DOCTYPE HTML>
<html>
<head>
    <script src="jquery.js"></script>
    <script src="../jquery.mockjax.js"></script>
    <title>MockJax Tests</title>
  </head>
<body>
    <h1>A MockJax test.</h1>
    <p>Check the console for results.</p>
    <script>

        $.mockjax({
          url: "foo.html",
          responseTime: 20000,
          responseText: "Hi! I am mockjax."
        });

        $.ajax({
          async: false,
          url: 'foo.html',
          success:function(data){
            console.log(data);
          },
          error:function(data){
            console.log('It doesn’t work that way :(');
          }
        });

    </script>
</body>
</html>

I have also implemented a test using CasperJS and Mockjax (within casper.evaluate), with similar results.

Below is the CasperJS code snippet:

var casper = require("casper").create({
  verbose: true,
  logLevel: 'error',
  clientScripts: ["node_modules/jquery-mockjax/jquery.mockjax.js"]
});

casper.on('remote.message', function(msg) {
  this.echo('remote message caught: ' + msg);
})

casper.start('http://der-zyklop.de/', function() {
  this.evaluate(function () {

    $.mockjax({
      url: "/blog/feed",
      responseTime: 20000,
      responseText: "Hi! I am mockjax!"
    });

    $.ajax({
      async: false,
      url: '/blog/feed',
      success:function(data){
        console.log(data);
      },
      error:function(data){
        console.log('It doesn’t work that way :(');
      }
    });

  });
});

casper.run();

If you have CasperJS installed, you can run the code by npm install jquery-mockjax followed by casperjs test.js. The output should be generated in less than 20 seconds.

For more details, you can refer to my blog article here.

Answer №1

Mockjax doesn't currently support blocking delays. The code snippet shows that it requires the request to be asynchronous in order to function properly:

If (requestSettings.async === false) {
    // TODO: Implement a blocking delay
    process();
} else {
    this.responseTimer = setTimeout(process, parseResponseTimeOpt(mockHandler.responseTime) || 50);
}

To make this work, you must set async: true. In doing so, you will need to wait within the casper context because the program will proceed without waiting for the response.

Casper.start(url, yourEvaluateFunction).wait(25000).run();

Implementing a true blocking delay in JavaScript is challenging and may involve busywaiting, which would stall all other processes as JavaScript is single-threaded.

Answer №2

Indeed, @artjom-b is absolutely correct. The responseTime feature has not been implemented for non-async requests because there is no logical reason to do so in terms of code execution (given that the ajax request will always be synchronous anyway, why introduce a delay?). However, you can create a custom response function (instead of using responseText) and simulate a delay by utilizing a simple setTimeout() along with our latest async response functionality:

$.mockjax({
  url: 'foo.html',
  response: function(settings, done) {  // introducing the "done" parameter makes this asynchronous
    var self = this;
    setTimeout(function(){
      self.responseText = "Hi! I am mockjax.";
      done();   // marks the end of the asynchronous action
    }, 20000);  // providing a 20 second delay here
  }
});

NOTE: To access this feature, you must have Mockjax version 1.6.0 or higher installed!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The AJAX-MYSQL request returned a "undefined" error with a 200 OK response code

I am currently working on developing an AJAX application that allows users to input a user's ID and have all corresponding information automatically populate the remaining text fields. For example, if the user types in the ID number "1234", the fields ...

Internet Explorer 9 terminates POST requests using XDomainRequest

I have been implementing a cross-domain Ajax call in my project. Here is the code snippet I used: if (window.XDomainRequest) // Checking if XDR is supported by the browser. { xdr = new XDomainRequest(); // Creating a new XDR object. if (xdr) { ...

Enhancing Form Validation with Jquery: SSN Pattern Matching, Input Masking, and Conditional Validation

Struggling with getting the Jquery Validation to cooperate with specific rules. The SSN field is masked with SSN format, and I need the validation to prevent submission unless it's a complete SSN. There's a regex function that rejects non-SSNs, ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. https://i.sstatic.net/5bHFO.png It displays "Sorted by ascending o ...

Retrieve elements within an element using its reference

<div ref={location} className={style.locations}> {locations.map(loc => ( <span onClick={onClick}> {loc.name} </span> ))} </div> My goal is to manipulate the <span> elements w ...

The progress counter page method has been prematurely halted

Currently, I am experiencing a situation where I have a complex process running during a standard postback. In order to track the progress of this operation, I have implemented a page method that is called by a JavaScript function at intervals. The simple ...

Implementing React selectors to manage the state changes on page load and when a user

I'm currently delving into React selectors with ReSelect, and while things seem to be going well, I have a feeling that there may be an issue in my logic. 1 - Upon receiving an AJAX response, I obtain a list of "categories" consisting of id, name, an ...

The Jquery navigation and image display features are experiencing technical difficulties in Internet Explorer

My website is currently in the development stage and functions well on all browsers except for IE10. Interestingly, both the menu bar and photo gallery, which rely on Jquery, are not functioning properly in IE10. Below is the code snippet: <script ty ...

Required inputs do not disrupt the form's action flow

Here is the HTML code that I am working with: function document_save_changes(){ if (is_key_dirty == true){ var elm = document.getElementById('set_doc_button'); key_change_warning(elm, 'D'); return; } if (document_save_warning('A ...

Unable to make changes while state transition is in progress

I want to update the state value based on the result of a promise method. To have optimistic updates, I set the state value before an asynchronous operation. If the operation fails, the state is reset. componentWillMount(){ this.setState({notify: this ...

Guide on serializing an object containing a file attribute

I'm currently working on creating a small online catalog that showcases various housing projects and allows users to download related documents. The data structure I am using is fairly straightforward: each project has its own set of properties and a ...

Activate the service function within the identical service

Currently, I am facing an issue while trying to call a function within the same AngularJS service. In my controller, I am able to successfully call the 'geocoding' function without any problems. However, within the 'geocoding' functio ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

Why is it necessary to include 'export' when declaring a React component?

When working with React (ES6), there seems to be two variations that I encounter: class Hello extends React.Component { ... } and sometimes it looks like this: export class Hello extends React.Component { ... } I'm curious about the significance o ...

Update the section tag upon submission using jQuery on a jQuery Mobile HTML page

I have integrated a jquerymobile template into Dreamweaver 6.0 to create a mobile app interface. The home screen features four buttons - specifically, View, Create, Update, Delete. Upon clicking the Create button, a new screen is opened (each screen corres ...

Dealing with error responses and dynamic notifications while utilizing AJAX form submissions in the Devise authentication

Currently, in my project using devise, I have implemented a process for submitting all devise forms - such as sign up, login, and forgot password forms - using ajax by adding remote: true. However, I am facing challenges in handling the display of error ...

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

Error: Webpack module is not a callable function

I have been developing a backend system to calculate work shifts. I am currently facing an issue with posting user input using a module located in services/shifts. While the getAll method is functioning properly, I encounter an error when trying to post da ...

Styling nested divs in CSS

I am experiencing an issue where the child divs within parent divs are overflowing outside of the parent divs. To get a better understanding of the problem, please try running the code below in a browser: My goal is to align the innermost divs horizontall ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...