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

使用MSW测试Angular服务时出现超时问题

问题:使用MSW测试Angular服务时的异步超时与断言检测异常

补充说明

  • 仅在测试阶段出现问题,运行ng serve并使用MSW提供数据时一切正常。

背景

最近接触到mswjs,打算用Mock Service Worker测试前端服务,不用依赖后端进度,也不用手写模拟服务类,已经按照文档完成所有配置。

遇到的具体问题

  • 初始运行测试时,收到提示:spec 'UserService should get list of users' has no expectations
  • 在subscribe回调末尾添加done()调用后,出现超时错误:
    Error: Timeout - Async function did not complete within 3000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL) in node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 7609)
    
  • 尝试在Karma中把默认超时时间增加到30000ms,没有效果;改用waitForAsync后测试无错误通过,但本质是测试用例仍未检测到期望断言。
  • 网上找到的示例大多是用模拟服务和fakeasync的方案,对当前场景不适用。

相关代码

Angular服务代码

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private url = 'http://localhost:3000/api/users';
  constructor(private http: HttpClient) { }

  getUser(id: string): Observable<User> {
    return this.http.get<User>(`${this.url}/${id}`);
  }

  listUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.url);
  }
}

测试代码

describe('UserService', () => {
  let service: UserService;
  beforeAll(() => {
    worker.start();
  });
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
    });
    service = TestBed.inject(UserService);
  });

  afterAll(() => {
    worker.stop();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should get list of users', (done) => {
    service.listUsers().subscribe((data) => {
      expect(data.length).toBe(5);
      done();
    });
  })
});

Worker配置代码

const handlers = [
    rest.get('http://localhost:3000/api/users', (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json(users))
    })
]
export const worker = setupWorker(...handlers)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:35:22