CasperJS 再次等待资源

CasperJS waitForResource again

我正在使用

.waitForResource('/auth')
.then( .... )
.waitForResource('/auth')
.then( .... )

等待对 /auth 的 ajax 调用完成,然后再验证 UI 响应。

但是,对 /auth 的后续调用似乎会立即继续,因为它已经加载了该资源。

有什么方法可以告诉 casperJS 再次等待,或者清除该资源以便它认为它不会为第二个请求加载?

原来它在工作,我只需要一个 .wait(250) 用于 UI 更新之前的后续调用。

如果有人感兴趣,我制定了一个通用方法来捕获所有 Ajax 请求并强制等待 250 毫秒,因此您无需执行

.waitForResource('/my/resource')
.wait(250)

而是将其添加到您的测试中,或将其加载为包含

/** 
 * Auto waitForResource on all Ajax requests.
 * Inserts a 250ms delay after load to allow any page renders with response   
 */
casper.options.onResourceRequested = function (casper, requestData){
    //is this Ajax..
    var isAjax = requestData.headers.some(function(header) {
        return (header.name == "X-Requested-With" && header.value == "XMLHttpRequest");
    });

    if(isAjax){
        casper.waitForResource(requestData.url, function(){
            casper.wait(250); //wait quarter of a sec for any page render after an ajax load...
        }, function(){
            console.error("AJAX request for " + requestData.url + " timed out.")
        }, 10000);
    }
}

然后它将自动等待所有 ajax 请求,并插入 250 毫秒的延迟以供 UI 更新。

Is there some way to tell casperJS to wait again, or clear that resource so it doesn't think it has loaded for the second request?

是的,这正是您可以做的。您可以通过重新初始化资源数组告诉 CasperJS 清除它之前看到的所有资源:

casper.resources = [];

如果您不想那样具有破坏性,您可以模仿casper.resourceExists()函数如何查找资源并仅删除那些:

casper.forgetResources = function(test){
    "use strict";
    this.checkStarted();
    var testFn,
        indexes = [],
        utils = require('utils');
    switch (utils.betterTypeOf(test)) {
        case "string":
            testFn = function _testResourceExists_String(res) {
                return res.url.search(test) !== -1 && res.status !== 404;
            };
            break;
        case "regexp":
            testFn = function _testResourceExists_Regexp(res) {
                return test.test(res.url) && res.status !== 404;
            };
            break;
        case "function":
            testFn = test;
            if (phantom.casperEngine !== "slimerjs")
                testFn.name = "_testResourceExists_Function";
            break;
        default:
            throw new CasperError("Invalid type");
    }

    this.resources.forEach(function(res, i){
        if (testFn(res)) {
            indexes.push(i);
        }
    });
    indexes = indexes.reverse();
    indexes.forEach(function(i){
        this.resources.splice(i, 1);
    });
    return this; // fluent API
};
casper.thenForgetResources = function(test){
    this.then(function(){
        this.forgetResources(test);
    });
    return this;
};

你会像这样使用它:

.waitForResource('/auth')
.then( .... )
.thenForgetResources('/auth')
.waitForResource('/auth')
.then( .... )