使用 Jasmine 和 Karma 在 Angular 单元测试中模拟基础服务

Mock Base service in Angular Unit test using Jasmine and Karma

我在 Angular 7 中有组件,它有服务作为构造函数参数。

@Component({
  selector: 'cc-schedule-list',
  templateUrl: './schedule-list.component.html',
  styleUrls: ['./schedule-list.component.scss']
 })
export class ScheduleListComponent implements OnInit {

  constructor(public accountActivityService: AccountActivityService) {}

  ngOnInit(): void {
  }

}

基础服务

@Injectable({
  providedIn: 'root'
})
export class BaseService {

  public commonHeaders: CommonHeaderModel;
  public legacyData: any;

  constructor(
    public httpClient: HttpClient,
    public appService: AppService
  ) {
      this.legacyData = this.appService.getDataFromLegacy();

      this.commonHeaders = {
        'sourceRequestID': 'KBB',
        'uuid': this.legacyData.UUID,
      };
  }

  getData(url: string, serviceHeaders: any, params?: any) {
    const headers = {...this.commonHeaders, ...serviceHeaders};
    return this.httpClient.get(url, {headers: headers, params: params});
  }
}

AccountActivityService

@Injectable({
  providedIn: 'root'
})
export class AccountActivityService {

  constructor(public base: BaseService) {
  }

  /**
   * getPendingPayments Function gets the all the pending payment transactions
   *
   * @returns All transactions on the account
   */
  getPendingPayments(electronicCardIdentifier, payeeAccountIdentifier) {
    return null; //return null at present
  }
}

ScheduleListComponent.spec 文件

describe('ScheduleListComponent',  () => {
  let component: ScheduleListComponent;
  let fixture: ComponentFixture<ScheduleListComponent>;
  let injector: any;
  let debugElement: DebugElement;
  let accountActivityService: MockAccountActivityService;

/** Mock Account Activity Service  ***/
  class MockAccountActivityService extends AccountActivityService {

   getPendingPayments() {
      return null;
    }
  }


  beforeEach( (() => {
    TestBed.configureTestingModule({
      declarations: [ ScheduleListComponent],
      imports: [
       ...
      ],
      providers: [ UserUtilService, { provide: AccountActivityService, useClass: MockAccountActivityService}],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
   .compileComponents();
    fixture = TestBed.createComponent(ScheduleListComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    accountActivityService = debugElement.injector.get(MockAccountActivityService);

   }));

  it('should create',  () => {
    expect(component).toBeDefined();
  });

 });

我总是收到这个错误 ***Angular 测试无法读取未定义或空引用的 属性 'UIID'。

可能是我的 ScheduleListComponent 没有使用 MockAccountActivityService 作为构造函数 parameter.Kindly 帮帮我

如果您正在执行组件的规范文件,则不需要包括 AccountActivityService,因为您正在测试组件而不是服务。

你可以模拟你的服务做:{ provide: AccountActivityService, useValue: {}}

尝试这样做:

ScheduleListComponent.spec 文件

describe('ScheduleListComponent',  () => {
  let component: ScheduleListComponent;
  let fixture: ComponentFixture<ScheduleListComponent>;


  beforeEach( (() => {
    TestBed.configureTestingModule({
      declarations: [ ScheduleListComponent],
      imports: [
       ...
      ],
      providers: [ UserUtilService, { provide: AccountActivityService, useValue:{}}],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
   .compileComponents();
    fixture = TestBed.createComponent(ScheduleListComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;

   }));

  it('should create',  () => {
    expect(component).toBeDefined();
  });

 });

试试看是否有效。