如何使用zombiejs按下一个执行慢速ajax调用的按钮后断言页面?

时间:2015-04-25 05:18:05

标签: javascript ajax zombie.js

我使用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.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'来设置全局等待时间,以使测试通过,但我不确定它是否是最佳方式。

1 个答案:

答案 0 :(得分:1)

我们可以在不传递回调的情况下调用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