-2

我目前正在实习生编写功能测试,并且遇到了一个小问题。

在我的测试套件的前面部分,我对 API 进行 ajax 调用以检索变量的值。设置的这个变量对于功能测试的下一步至关重要,因此我想暂停测试,直到从 ajax 调用返回变量。

我阅读了 Leadfoot 的 pollUntil() 函数,听起来它完成了我需要做的事情。我写了以下代码:

var valueThatChanges = 0;

// ... (some functional test setup stuff)

//Ajax call that sets value of valueThatChanges
.then(function() {
    return ajaxCall(valueThatChanges);
})

//valueThatChanges is initially 0 before/during ajax call
//Is set to a randomly generated value that is non-zero after response recieved
.then(pollUntil(function(valueThatChanges) {
        return valueThatChanges !== 0 ? true : null;
    },[valueThatChanges], 30000, 100))

    .then(function() { //On success
        console.log('Value is no longer zero.')
    }, function(error) { //On failure/timeout
        console.log(error)
    })
});

但是,这不起作用,因为尽管值valueThatChanges仍然为 0,但函数会立即进入成功回调。

我知道 pollUntil() 可能不是为了处理这种情况而设计的(因为我没有直接处理 pollUntil 中的 DOM 元素),但我不确定为什么它不适用于这种特定情况。

似乎 pollUntil() 没有在每次调用它的轮询函数时传递更新的变量。

pollUntil() 可以处理在变量值更改时触发事件吗?

4

1 回答 1

0

的一般用例pollUntil是您需要等待远程浏览器中发生某些事情的情况。例如,pollUntil常用于等待功能测试页面完全初始化:

// ---------------------
// functional test (in Node.js)
this.remote.get('testpage.html')
    .then(pollUntil('return window.pageIsReady ? true : null'))
    // rest of test

// ---------------------
// remote test page (in the browser)
<script>
    var pageIsReady = false;
    require( ..., function ( ... ) {
        // do setup stuff
        pageIsReady = true;
    });
</script>

如果您在测试设置中执行一些涉及浏览器的异步操作,请从before测试套件中的函数返回一个 Promise,该函数将在异步操作完成时解析。

var valueThatChanges;

registerSuite({
    before: function () {
        return new Promise(function (resolve) {
            // Assuming ajaxCall calls a callback when it's finished:
            ajaxCall(function (newValue) {
                valueThatChanges = newValue;
                resolve();
            });
        });
    },

    test1: function () {
        return this.remote
            // rest of test
    },

    // ...
});
于 2015-08-09T20:35:12.307 回答