2017-05-05 84 views
1

我試圖在腳本花費太長時間加載時測試我的網站的行爲。我知道如何完全阻止請求,以便通過向主機文件添加內容來返回404,但不知道如何強制請求不完整。如何使AJAX呼叫掛起

例,

127.0.0.1 translate.google.com # this blocks google translate from loading (404) 

相反,我想提出translate.google.com 不是x秒響應

我使用requirejs加載我的劇本,我注意到,超時行爲不同於404

我添加了一個模塊,允許谷歌翻譯進行選擇性要求,當我通過主機文件阻止它,該網站的行爲是正確的。腳本超時後,該站點無法加載。

// http://stackoverflow.com/questions/14164610/requirejs-optional-dependency 

define("optional", [], { 
    load: function (moduleName, parentRequire, onload, config) { 
     var onLoadSuccess = function (moduleInstance) { 
      // Module successfully loaded, call the onload callback so that 
      // requirejs can work its internal magic. 
      onload(moduleInstance); 
     } 

     var onLoadFailure = function (err) { 
      // optional module failed to load. 
      var failedId = err.requireModules && err.requireModules[0]; 
      console.warn("Could not load optional module: " + failedId); 

      // Undefine the module to cleanup internal stuff in requireJS 
      requirejs.undef(failedId); 

      // Now define the module instance as a simple empty object 
      // (NOTE: you can return any other value you want here) 
      define(failedId, [], function() { return {}; }); 

      // Now require the module make sure that requireJS thinks 
      // that is it loaded. Since we've just defined it, requirejs 
      // will not attempt to download any more script files and 
      // will just call the onLoadSuccess handler immediately 
      parentRequire([failedId], onLoadSuccess); 
     } 

     parentRequire([moduleName], onLoadSuccess, onLoadFailure); 
    } 
}); 
+0

你能詳細說明你正在測試什麼嗎?您可以簡單地延遲在'onLoadSuccess'回調處理程序中使用'setTimeout((=)onload(moduleInstance),4 * 1000)'調用'onload'方法4秒延遲。 – alpeware

+0

嘗試測試腳本超時發生的情況。當它返回404時,它的行爲是正確的,當它超時時,它行爲不正確。 – MPavlak

回答

0

您需要測試它與您控制的網站。最簡單的解決方案是使用你自己的本地主機和一些等待幾秒鐘的腳本。

一個簡短的PHP例子等待30秒會是什麼樣子:

<?php 
    sleep(30); 
    echo 'DONE'; 

只是增加了秒睡眠狀態,直到您的應用程序超時。

Here is another solution in Node.js

UPDATE:

下一步是重定向你想在你的主機文件超時的URL(如你的問題):

127.0.0.1 translate.google.com 

運行本地Apache server (127.0.0.1是本地主機的標準配置),並將以下.htaccess文件放入您的apache根目錄(通常爲「htdocs」):

DirectoryIndex index.php 
RewriteEngine on 
RewriteRule ^(.*)$ index.php [QSA,L] 

然後,只需將上例中的PHP示例放入一個名爲index.php的文件(通常爲「htdocs」)。

然後你的本地服務器應該響應這個呼叫,你可以調整響應時間,直到你超時。

+0

從技術上講,我可以做到這一點。但是,我不想將所有外部腳本移動到我的項目中,只是爲了測試他們未能響應時會發生什麼。 – MPavlak

+0

只要您的應用程序在您的瀏覽器中運行,您不必。您可以調整您的本地主機文件,以便將所需的請求重定向到本地主機(127.0.0.1)。 – dcman

+0

指向本地腳本,我不提供返回404不會返回404它不會掛起 – MPavlak