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

使用Oboe.js、oboe-promise与Jest时异步测试超时问题求助

解决Oboe.js + Jest测试超时问题

我最近用Oboe.js、oboe-promise配合Jest做开发时碰到了头疼的问题:Jest测试一直超时,哪怕把超时时间调到60000ms也没用,但同样的代码在Jest环境外跑完全正常。先贴一下我的代码:

业务代码

"use strict";
const oboe = require('oboe-promise')
const { Readable } = require('stream')

class Example {
  async run() {
    const json = JSON.stringify([{obj1: {name: 'example', value: 5}}, {obj2: {type: 'other', value: 0}}])
    const strm = Readable.from(json)
    return await oboe(strm)
      .node('{type}', (node) => {
        node.name = node.type
        delete node.type
        return node
      })
      .run()
  }
}

module.exports = Example

测试代码

"use strict"
// Classes
let Example // class under test
// Objects
let example // object under test

describe('Example', () => {
  beforeEach(() => {
    Example = require('../../src/Example')
    example = new Example()
  })

  test('run', async () => {
    expect(await example.run()).toEqual(JSON.stringify([{obj1: {name: 'example', value: 5}}, {obj2: {value: 0, name: 'other'}}]))
  })
})

问题分析

你碰到的超时问题其实是两个点共同导致的:

  1. Stream在Jest环境中未正确结束:Readable.from(json)创建的流,在Jest环境里可能没有正确触发end事件,导致oboe的Promise一直处于pending状态,永远不会resolve,自然就超时了。
  2. 断言类型不匹配:oboe处理完成后返回的是解析后的JSON对象,但你的测试里用JSON.stringify后的字符串去做对比,就算stream正常结束,这个断言也会失败。

解决方案

1. 修正Stream的创建方式

把Readable.from(json)替换成手动构造Readable流,明确推送数据并结束,确保oboe能收到结束信号:

// 替换原来的strm创建代码
const strm = new Readable({
  read() {
    this.push(json);
    // 推送null表示流结束
    this.push(null);
  }
});

2. 修正断言逻辑

去掉JSON.stringify,直接对比处理后的对象:

test('run', async () => {
  expect(await example.run()).toEqual([
    {obj1: {name: 'example', value: 5}},
    {obj2: {value: 0, name: 'other'}}
  ])
})

修改后的完整业务代码

"use strict";
const oboe = require('oboe-promise')
const { Readable } = require('stream')

class Example {
  async run() {
    const json = JSON.stringify([{obj1: {name: 'example', value: 5}}, {obj2: {type: 'other', value: 0}}])
    const strm = new Readable({
      read() {
        this.push(json);
        this.push(null);
      }
    });
    return await oboe(strm)
      .node('{type}', (node) => {
        node.name = node.type
        delete node.type
        return node
      })
      .run()
  }
}

module.exports = Example

这样修改后,测试应该就能正常通过,不会再超时了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:57:49