【问题标题】:spyon() or jasmine.createobject to return observable arrayspyon() 或 jasmine.createobject 返回可观察数组
【发布时间】:2018-05-10 13:44:26
【问题描述】:

我正在尝试为 Angular 应用程序编写单元测试测试用例。我有一个返回 Observable 的服务,我目前正在尝试测试它。

我尝试过使用 Observable.of() 似乎不起作用。 以下是文件..

使用 httpclient 返回 observable 的服务方法。我试图窥探 具有可观察到数组的返回值。

terminal-carding.service.ts

 getTerminalCompanies() {
return this.http.get(this.maintenanceSharedService.getTerminalCompaniesUrl())
  .map(this.extractData)
  .catch(this.handleGetTerminalCompaniesError)

}

terminal-carding.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AgGridModule } from 'ag-grid-angular/main';
import { TableWidgetComponent } from '../../../widgets/table-widget/table-widget.component';
import { TerminalCardingComponent } from './terminal-carding.component';
import { TerminalCardingService } from './terminal-carding.service';
import { AppService } from './../../../app.service';
import { UtilService } from '../../../shared/util.service';
import { DashboardSharedService } from './../../../shared/dashboard-shared.service';
import { TableWidgetService } from '../../../widgets/table-widget/table-widget.service';
import { SecuritySharedService } from '../../../shared/security-shared.service';
import { MaintenanceSharedService } from '../../../shared/maintenance-shared.service';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Observable} from 'rxjs/observable';
import { HttpClientModule } from '@angular/common/http';
import { BaseHttpClientService } from '../../../shared/common/base-http-client.service';

fdescribe('TerminalCardingComponent', () => {
  let component: TerminalCardingComponent;
  let fixture: ComponentFixture<TerminalCardingComponent>;
  let maintenanceSharedService: MaintenanceSharedService;
  let service: TerminalCardingService;
  let getMaintenanceModuleAuthPermissionsSpy;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        AgGridModule.withComponents([]),
        HttpClientModule,
        FormsModule
      ],
      declarations: [
        TerminalCardingComponent,
        TableWidgetComponent,
      ],
      providers: [
        AppService,
        UtilService,
        DashboardSharedService,
        TableWidgetService,
        SecuritySharedService,
        MaintenanceSharedService,
        TerminalCardingService,
        BaseHttpClientService
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    service = TestBed.get( TerminalCardingService );
    maintenanceSharedService = TestBed.get( MaintenanceSharedService );
    getMaintenanceModuleAuthPermissionsSpy = spyOn(maintenanceSharedService, 'getMaintenanceModuleAuthPermissions').and.returnValue({});
    fixture = TestBed.createComponent(TerminalCardingComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should resolve test data', async(() => {
    const terminalCompanies = [{
      terminalCompany: 'aaa'
    },
    {
      terminalCompany: 'bbb'
    },
    {
      terminalCompany: 'ccc'
    }];
    const spy = spyOn(service, 'getTerminalCompanies').and.returnValue(Observable.of(terminalCompanies));
      component.ngOnInit();
      fixture.detectChanges();
      console.log(component.terminalCompanies[0].terminalCompany);
      expect(component.terminalCompanies[0].terminalCompany).toEqual(terminalCompanies[0].terminalCompany);
    }));

  });

   Error: i am getting following error....
Failed: observable_1.Observable.of is not a function

【问题讨论】:

  • Observable.of() 也应该可以,你使用的是哪个 RxJS 版本?
  • 你遇到了什么错误?
  • 我们正在使用 rxjs 版本 5.4.1 ...我也尝试过以下方法....
  • 我们正在使用 rxjs 版本 5.4.1 ...我也尝试过以下方法.... it('should resolve test data', async(() => { const terminalCompanies = [{ terminalCompany: 'aaa' }]; const spy = spyOn(service, 'getTerminalCompanies').and.returnValue(Observable.of(terminalCompanies)); .... 我得到以下错误... 预期 [ Object({ terminalCompany : 'aaa' }) ] 等于 。错误:预期 [ Object({ terminalCompany: 'aaa' }) ] 等于 .
  • 您进行了两次间谍活动,并且 ` const cardingService = jasmine.createSpyObj('TerminalCardingService', ['getTerminalCompanies']) .and.returnValues({});` 将不起作用。

标签: angular unit-testing karma-jasmine


【解决方案1】:

这里有问题

expect(component.terminalCompanies).toEqual(terminalCompanies);

问题是,您正在执行array === array,它返回false

因此,要进行测试,您应该比较数组中的值。即

expect(component.terminalCompanies[0].terminalCompany).toEqual(terminalCompanies[0].terminalCompany);

希望对你有帮助...

【讨论】:

  • 我已根据您的建议更新了代码,但仍然出现“失败:observable_1.Observable.of 不是函数”之类的错误,并且还更新了最新代码
  • @priya ,因为Failed: observable_1.Observable.of is not a function 是错误,你需要从RXJS 导入of。像这样添加导入 -> import "rxjs/add/observable/of"; // For RxJs 5.x
  • 我按照您的建议进行了尝试,但仍然遇到相同的错误...即 import { of } from 'rxjs/observable/of';.. 并尝试如下所述.. . const spy = spyOn(service, 'getTerminalCompanies').and.returnValue(Observable.from(terminalCompanies));...但我仍然会得到同样的错误 Failed: observable_1.Observable.from is not a function
  • @priya,问题是:of 没有正确导入。 RxJS 在不同的 RxJS 版本中有不同的语法来导入操作符。所以试试这个 -> import 'rxjs/add/observable/of';
  • 我按照你的建议试过了,但我还是遇到了同样的错误,比如 Failed: observable_1.Observable.of is not a function
猜你喜欢
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多