繁体   English   中英

Angular 中的 Mock Base 服务 使用 Jasmine 和 Karma 进行单元测试

[英]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 testing Cannot read property 'UIID' of undefined or null reference。

可能是我的 ScheduleListComponent 没有将 MockAccountActivityService 作为构造函数参数。请在这里帮助我

如果您正在编写组件的规范文件,则不需要包含 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();
  });

 });

试试这是否有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM