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

求助:jest-mock-extend生成的Mock接口无法触发Observable.of致测试超时

问题原因与解决方法

你的测试超时是因为jest-mock-extend创建的Mock对象是一个Proxy实例,在RxJS的of操作符处理它时触发了未捕获的内部错误,但你没有设置错误处理回调,导致done()始终无法被调用,最终测试超时。

解决方案1:添加错误处理回调

在订阅时补充error回调,捕获并传递错误,便于快速定位具体问题:

import { mock } from 'jest-mock-extended';
import { of } from 'rxjs';

interface TestInterface {
  dummyProperty: string;
}

describe('Test Observable.of mock interface implementation', () => {
  it('test Observable of an Interface mock', (done) => {
    const mockTestInterface = mock<TestInterface>();

    of(mockTestInterface).subscribe({
      next: testObject => {
        expect(testObject).toBeTruthy();
        done();
      },
      error: err => {
        done(err); // 传递错误,方便排查具体问题
      }
    });
  });
});

解决方案2:手动创建Mock对象

绕过jest-mock-extend的Proxy式Mock,直接构建符合接口的普通Mock对象:

import { of } from 'rxjs';

interface TestInterface {
  dummyProperty: string;
}

describe('Test Observable.of mock interface implementation', () => {
  it('test Observable of an Interface mock', (done) => {
    // 手动创建符合接口的Mock对象,避免Proxy引发的问题
    const mockTestInterface = {
      dummyProperty: 'mock-value'
    } as TestInterface;

    of(mockTestInterface).subscribe(testObject => {
      expect(testObject).toBeTruthy();
      done();
    });
  });
});

解决方案3:用lastValueFrom替代done回调

利用RxJS的工具函数处理异步逻辑,避免回调嵌套,同时自动捕获错误:

import { mock } from 'jest-mock-extended';
import { of, lastValueFrom } from 'rxjs';

interface TestInterface {
  dummyProperty: string;
}

describe('Test Observable.of mock interface implementation', () => {
  it('test Observable of an Interface mock', async () => {
    const mockTestInterface = mock<TestInterface>();
    const result = await lastValueFrom(of(mockTestInterface));
    expect(result).toBeTruthy();
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:20:30