摩卡可能会推迟柴的期望

时间:2013-12-25 14:26:45

标签: javascript selenium-webdriver mocha chai

我正在用mocha,selenium和chai做一些测试驱动的开发,我是这些库的初学者,我问我是否已经做好了事情? 这是我的functional_tests.js

的一部分
test.it('Hamid visits the first page of tests', function(){
    // Hamid visits the home page of the test plateform he heard about
    driver.get('file:///home/marouane/Projects/iframe_test/test_template.html') ;

    // he noticed the title and the header of the page mention Test Template
    driver.getTitle().then(function(title){
        expect(title).to.contain('Test Template');
    });

    driver.findElement(webdriver.By.tagName('h1')).then(function(element){
        expect(element).to.contain('Test Template');
    });
    // he is invited to enter a URL for the page he wants to test
    driver.findElement(webdriver.By.id('input-url'), function(element){
         expect(element).to.equal('Enter a url');
    });

这是我测试的html页面:

<!DOCTYPE html>
<html>
<head>
    <title>Test Template</title>
</head>
<body>
<h1></h1>
</body>
</html>

我希望在第二个 chai expectation 上得到一个断言错误,但我以这个错误结束了:

  

NoSuchElementError:无法找到元素:{“method”:“id”,“selector”:“input-url”}。

可能是我做错了,而且回调函数是延迟的。

1 个答案:

答案 0 :(得分:0)

我没有在这里组织运行您的代码,但通过检查您的代码我相信有两个问题:

  1. it回调中的代码是异步的,但您不使用done回调来表示测试已完成。虽然使用WebDriverJS的承诺风格使它看起来更像同步代码,而"control flows"(即WebDriverJS的术语)也使异步代码看起来是同步的,但事实仍然是使用WebDriverJS本质上是异步的。

  2. 您混合使用两种不同风格的WebDriverJS函数。也就是说,你混合了承诺和延续。您对driver.getdriver.getTitle的调用以及对driver.findElement的第一次调用都是使用承诺(显式或隐式)。但是,对driver.findElement的最后一次调用使用的是延续而不是承诺。所以第一次调用使用控制流设施,但最后一次没有。最后一个不能使用控制流工具,因为此工具只管理 promises ,而你的lass调用使用continuation而不是promise。因此,您的expect来电不会按照您认为的顺序执行。

  3. 这样的事情可以解决我上面提到的问题:

    test.it('Hamid visits the first page of tests', function(done){
        // Hamid visits the home page of the test plateform he heard about
        driver.get('file:///home/marouane/Projects/iframe_test/test_template.html') ;
    
        // he noticed the title and the header of the page mention Test Template
        driver.getTitle().then(function(title){
            expect(title).to.contain('Test Template');
        });
    
        driver.findElement(webdriver.By.tagName('h1')).then(function(element){
            expect(element).to.contain('Test Template');
        });
    
        // he is invited to enter a URL for the page he wants to test
        driver.findElement(webdriver.By.id('input-url')).then(function(element){
             expect(element).to.equal('Enter a url');
             done();
        });
    });
    

    只有两处变化:

    1. 我已将done参数添加到it(第一行)的回调中,并且我在包含您上次回调的回调中添加了对done()的调用expect

    2. 我已将最后一次调用driver.findElement更改为使用承诺而非延续的调用。