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

Jest测试报错:Cannot read property 'runnable' of null 求助排查

问题根源与解决方案

问题本质

这个错误的核心原因是 selenium-webdriver/testing 模块是为Mocha等传统测试框架设计的,它依赖了Mocha测试上下文里的this.runnable属性,但Jest并不提供这个上下文,再加上Zone.js的补丁在拦截测试执行时进一步清空了上下文,导致this变成null,从而触发了Cannot read property 'runnable' of null的报错。

简单说:你用了一个专为Mocha打造的selenium测试封装,却在Jest+Zone.js的环境里跑,两者的上下文机制完全不匹配。

解决方案

1. 弃用selenium-webdriver/testing模块(推荐)

直接使用selenium-webdriver的原生API,结合Jest自带的异步测试支持(async/await)来编写用例,完全避开兼容性问题。

错误写法示例(依赖selenium测试模块):

const { describe, it } = require('selenium-webdriver/testing');
const { Builder } = require('selenium-webdriver');

describe('My Test', function() {
  let driver;

  before(function() {
    driver = new Builder().forBrowser('chrome').build();
  });

  it('should do something', function() {
    return driver.get('https://example.com')
      .then(() => driver.getTitle())
      .then(title => expect(title).toBe('Example Domain'));
  });

  after(function() {
    return driver.quit();
  });
});

修正后的写法(使用Jest原生语法):

const { Builder } = require('selenium-webdriver');

describe('My Test', () => {
  let driver;

  beforeAll(async () => {
    driver = await new Builder().forBrowser('chrome').build();
  });

  it('should do something', async () => {
    await driver.get('https://example.com');
    const title = await driver.getTitle();
    expect(title).toBe('Example Domain');
  });

  afterAll(async () => {
    await driver.quit();
  });
});

2. 若必须使用selenium-webdriver/testing模块(不推荐)

可以尝试禁用Zone.js对Jest测试的代理补丁,在测试文件开头添加以下代码:

require('zone.js/dist/zone-patch-jest');
// 或者直接关闭ProxyZone
const Zone = require('zone.js');
Zone.currentSpec = null;

不过这种方法可能会引发其他Zone相关的问题,所以更建议用第一种方案彻底替换测试写法。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:10