首页 > 解决方案 > 使用 Nodejs 和 Mocha 运行 Selenium 时出现“NoSuchSessionError”

问题描述

我正在用 JavaScript 中的 Selenium 和 Mocha 编写一个测试用例。节点版本为 v10.10.0。摩卡版本为 v5.2.0。

这是我的测试代码:

require('chromedriver');
const assert = require('assert');
const {Builder, By, until} = require('selenium-webdriver');

var capabilities = {
    'browserName' : 'chrome',
    'chromeOptions' : {
      'args' : ["--disable-plugins"]
    }
}

describe('Checkout Formy', () => {
    let driver;

    before(async () => {
        driver = await new Builder().withCapabilities(capabilities).build();        
    });

    it('Large page scroll', async () => {
        try {
            await driver.get('http://formy-project.herokuapp.com/scroll');               

            // Find form input at the bottom of the page
            let name = await driver.findElement(By.id('name'));

            // Scroll to the name input field 
            driver.executeScript('arguments[0].scrollIntoView()', name);     
            driver.sleep(300);   
            name.sendKeys('Dale Nguyen');

            // Find date field
            let date = await driver.findElement(By.id('date'));
            date.sendKeys('01/01/2018');  

            // // assertion codes...   

            // done();
        } catch (error) {
            console.log(error);            
        }

    });

    after(() => driver.quit());
})

我第一次运行良好,然后第二次或第三次运行此测试,它显示警告。

(node:45609) UnhandledPromiseRejectionWarning: NoSuchSessionError: invalid session id
  (Driver info: chromedriver=2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8),platform=Mac OS X 10.12.6 x86_64)
    at Object.checkLegacyResponse (/Users/dnguyen/Documents/projects/unit-test/selenium-javascript/node_modules/selenium-webdriver/lib/error.js:585:15)
    at parseHttpResponse (/Users/dnguyen/Documents/projects/unit-test/selenium-javascript/node_modules/selenium-webdriver/lib/http.js:533:13)
    at Executor.execute (/Users/dnguyen/Documents/projects/unit-test/selenium-javascript/node_modules/selenium-webdriver/lib/http.js:468:26)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:45609) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:45609) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminatethe Node.js process with a non-zero exit code.

有什么想法吗?谢谢,

标签: seleniumtestingselenium-webdriverasync-awaitmocha.js

解决方案


试试这样设置

var selenium = require('selenium-webdriver');
var capabilities = selenium.Capabilities.chrome();

capabilities.set('chromeOptions', {
      'args': ['--disable-plugins']
});

var driver = new selenium.Builder().forBrowser('chrome').withCapabilities(capabilities).build();

推荐阅读