我正在使用zombiejs来测试具有按钮的html页面,单击该按钮时,它将发出ajax调用,并在几秒钟后更新页面。

/static/ajax-button.html

<html>
<head>
    <script src="./js/jquery-1.11.2.js"></script>
    <script>
        function fetchResponse() {
            $.get('/delay/8', function(data) {
                $('#response').text(data);
            });
        }
    </script>
</head>
<body>
<button id="mybutton" onclick="fetchResponse()">Click me to fetch response</button>
<div id="response">please wait for a while ...</div>
</body>
</html>


app / app.js

使用expressjs:

app.get('/delay/:seconds', function(req, res) {
    const seconds = req.param("seconds") || 1;
    setTimeout(function() {
        res.send('Delayed Hello World in ' + seconds + 's!')
    }, seconds * 1000);
});


测试/按一下按钮spec.js

const Browser = require('zombie');
const moment = require('moment');
const expect = require('expectations');

// We're going to make requests to http://example.com/???
// Which will be routed to our test server localhost:3000
Browser.localhost('example.com', 3000);

describe('browser.pressButton', function() {

    const browser = new Browser();

    this.timeout(10000);

    before(function(done) {
        console.log("######## browser.visit");
        browser.visit('/static/ajax-button.html', done);
    });

    before(function(done) {
        console.log("######## browser.pressButton");
        browser.pressButton('#mybutton', done);
    });

    it('should find "Delayed Hello World!" in page after a while', function(done) {
        console.log("######## testing");
        console.log(browser.html());
        browser.assert.status(200);
        browser.assert.text('#response', "Delayed Hello World in 8s!");
    });

});


但是当我使用mocha将其运行为:

mocha test/press-button-spec.js


它报告:

➜  zombiejs-test git:(master) ✗ mocha test/press-button-spec.js


  browser.pressButton
######## browser.visit
######## browser.pressButton
    1) "before all" hook


  0 passing (5s)
  1 failing

  1) browser.pressButton "before all" hook:
     Timeout: did not get to load all resources on this page


似乎browser.pressButton('#mybutton', done);超时,因为zombiejs的默认等待时间是5000ms,但是ajax调用需要8s才能完成。

如何解决?



您也可以从此https://github.com/freewind/zombiejs-test中找到代码

克隆后,运行:

node app/app.js
mocha test/press-button-spec.js




更新:

我可以添加browser.waitDuration = '10s'来设置全局等待时间,以使测试通过,但是我不确定这是否是最佳方法。

最佳答案

我们可以调用browser.pressButton而不传递回调,然后在browser.wait中检查它们:

it('should find "Delayed Hello World!" in page after a while', function(done) {
    browser.pressButton('#mybutton');
    browser.wait(10000).then(function() {
        browser.assert.status(200);
        browser.assert.text('#response', "Delayed Hello World in 8s!");
    }).then(done, done)
});


https://github.com/freewind/zombiejs-test/blob/master/test/wait-spec.js#L28

07-26 04:16