开发者

Mocking out AJAX calls with Dojo XHR

开发者 https://www.devze.com 2023-02-09 11:58 出处:网络
I\'m attempting to mock the response of a dojo xhr request, but I haven\'t found a good solution. Ideally, I\'d like to see a solution similar to the jQuery mockjax plugin where I can set a specific

I'm attempting to mock the response of a dojo xhr request, but I haven't found a good solution.

Ideally, I'd like to see a solution similar to the jQuery mockjax plugin where I can set a specific call based on a url, e.g.:

 $开发者_运维问答.mockjax({
  url: '/restful/fortune',
  responseTime: 750,
  responseText: {
    status: 'success',
    fortune: 'Are you a turtle?'
  }
 });

My initial thought was to utilize the "/dojo/io/send" channel, but I haven't been able to get a modified response to be loaded after modifying the dojo Deferred object.

The other thought is to use a pass-through method that would determine if an actual xhr request should be made, e.g.:

function xhrRequest(xhrArgs) {
   if(shouldMock) {
      var fakeReturnJson = dojo.toJson({
        howdy: "that's odd!",
        isStrange: false
      }); 
      return fakeReturnJson;
   } else {
      dojo.xhr(xhrArgs);
   }

}

Can someone tell me the best way to go about mocking dojo xhr calls?

Thanks!


It's an old question, but I think you should do your mocking using Sinon.js

However you will need to put the following:

has: { native-xhr2: false }

into your dojoConfig for it to work in 1.8


I haven't heard of any Dojo specific libraries similar to Mockjax. But what I think you could try is use Mockjax with Dojo. This should be pretty easy to do since all you'll have to do is use JQuery during development only for testing with Mockjax and then remove it once development is complete.


I use your second suggestion. Currently, I have a transport layer (simple js class) and 2 implementations (XhrTransport and MockTransport). I then switch in which I need without changing the widget code. Widgets call the server with:

Controller.send(aServerCall); 

where aServerCall is a simple value object with the server endpoint, params and callback.

This way, you can add nice things to the controller that will apply to all server calls (such as logging, analytics, generic error handling...) and also mock out the entire server when doing unit tests. For the MockTransport, I simply return canned json data from static .js files in the format that the widget expects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号