You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Node.js结合Mocha运行无头Chrome时遇语法错误求助

解决Node.js+Mocha+无头Chrome测试的SyntaxError问题

问题根源

SyntaxError: Unexpected end of input是典型的语法结构不完整错误,你的代码存在两处未闭合的大括号:

  • test.describe('Browser Headless', function() {没有对应的闭合})
  • test.it("Headless with Chrome", function() {的函数体未完全闭合

额外问题修正

除语法错误外,代码还有两个影响测试正常运行的问题:

  • driver.quit是方法,必须加括号调用:driver.quit()
  • Selenium操作都是异步的,原代码未处理异步等待,Mocha会提前结束测试,导致结果不可靠

修正后的完整代码

var assert = require('assert');
var webdriver = require('selenium-webdriver'),
              By = webdriver.By,
              until = webdriver.until;
var test = require('selenium-webdriver/testing');  
var driver;
const timeOut = 15000;       

const chromeCapabilities = webdriver.Capabilities.chrome();
chromeCapabilities.set('chromeOptions', {args: ['--headless', '--disable-gpu','--no-sandbox','--disable-dev-shm-usage']});

var site_root_url = "file://" + __dirname + "/../../site"

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

test.describe('Browser Headless', function() {

  test.before(function() {
  });
  
  test.after(function() {
  });

  test.beforeEach(function() {
    // this.timeout(timeOut);
  });

  // test cases
  var url = "";

  test.it("Headless with Chrome", async function() {
    this.timeout(timeOut);    
    
    driver = new webdriver.Builder()
      .forBrowser('chrome')
      .withCapabilities(chromeCapabilities)
      .build();
      
    await driver.get("http://travel.agileway.net");
    const the_title = await driver.getTitle();
    assert.equal("Agile Travel", the_title);
    await driver.quit();
  });
}); // 闭合test.describe代码块

关键修正说明

  1. 补充test.describe末尾的闭合});,修复语法结构
  2. 将测试函数改为async,使用await等待所有异步操作完成,确保Mocha等待测试执行完毕
  3. 修正driver.quit()为方法调用,确保浏览器进程正常退出
  4. 用await替代then回调,代码逻辑更清晰

内容的提问来源于stack exchange,提问作者Qwe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:35:28