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

Angular 11 基于Jasmine编写测试用例遇TestBed.get废弃等错误求解

问题解决方案

问题1:TestBed.get废弃报错(TS6387)

Angular 9及以上版本已经废弃TestBed.get方法,统一使用类型更安全的TestBed.inject替代即可,直接替换原有调用语句:
原语句:httpTestingController = TestBed.get(HttpTestingController);
替换为:httpTestingController = TestBed.inject(HttpTestingController);

问题2:参数类型不匹配报错(TS2345)

该报错是因为你没有在测试模块的providers配置中注册要注入的EmployeeService,依赖注入容器找不到对应服务,无法完成注入,按以下步骤修复即可:

  1. 在TestBed.configureTestingModule的配置项中添加providers: [EmployeeService],注册待测试的服务
  2. 可以直接用TestBed.inject获取服务实例,省略老旧的inject函数写法,简化代码
    另外你定义的Employee接口重复声明了action属性,建议删除多余的声明避免冗余警告。

修正后的完整代码

employee模型

export interface Employee {
    name: string;
    desc: null | string;
    action: string;
    obj: Obj;
}

export interface Obj {
    empId: string;
    empName: string;
    reportTo: string;
    country: string;
    region: string;
    empStatus: string;
    department: string;
}

测试用例代码

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
// 替换为你自己的EmployeeService实际导入路径
import { EmployeeService } from './employee.service';
import { Employee } from './employee.model';

describe('DataAccessService', () => {
    let httpTestingController: HttpTestingController;
    let dataAccessService: EmployeeService;
    let traveller: Employee;
  
    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        // 新增注册EmployeeService
        providers: [EmployeeService]
      });
  
      httpTestingController = TestBed.inject(HttpTestingController);
      // 直接获取服务实例,不需要额外inject调用
      dataAccessService = TestBed.inject(EmployeeService);

      traveller = {
        name: 'Jane',
        desc: 'Jane',
        action: '',
        obj: {
          empId: 'Jane',
          empName: 'Jane',
          reportTo: 'TD1',
          country: 'USA',
          region: 'USA',
          empStatus: 'Inactive',
          department: 'HR - Marketing',
        }
      };
    });
  
    // 示例测试用例,可自行扩展其他测试逻辑
    it('服务应该正常实例化', () => {
      expect(dataAccessService).toBeTruthy();
    });
  });

内容的提问来源于stack exchange,提问作者Mr. Learner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 09:09:02