【问题标题】:Angular 4 unit test error "TypeError: Cannot read property 'subscribe' of undefined"Angular 4 单元测试错误“TypeError:无法读取未定义的属性‘订阅’”
【发布时间】:2018-02-14 04:37:41
【问题描述】:

在对 Angular 4 组件进行单元测试时,我卡住并不断出错。

这是我的组件:

order-detail.component.ts

@Component({
  selector: 'order-detail',
  templateUrl: 'order-detail.component.html',
  providers: [OrderService]
})
export class OrderDetailComponent implements OnInit {
  private order: Order;

  constructor(
    private orderService: OrderService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    this.getOrder();
  }

  private getOrder(): void {
    this.route.paramMap
      .map((params: ParamMap) => {
        if (+params.get('id') === 0) {
          this.router.navigateByUrl('/404', {skipLocationChange: true});
        }

        return params;
      })
      .switchMap((params: ParamMap) => this.orderService.getOrder(+params.get('id')))
      .subscribe((order: Order) => this.order = order);
  }
}

这里有一个服务:

order.service.ts

@Injectable()
export class OrderService {
  private ordersUrl = `${environment.apiUrl}/orders/`;

  constructor(private http: HttpClient) {}

  getOrder(id: number): Observable<Order> {
    return this.http.get(`${this.ordersUrl}${id}/`)
      .map(response => response as Order);
  }
}

我想在OrderServive 上设置一个间谍并用这样的测试对其进行单元测试:

order-detail.component.spec.ts

describe('Order detail component', () => {
  let fixture: ComponentFixture<OrderDetailComponent>;
  let page: Page;
  let activatedRoute: ActivatedRouteStub;
  const fakeOrder: Order = {
    id: 1,
    title: 'Test 1',
    contractor: {title: 'Contractor 1'} as Contractor,
  } as Order;

  class Page {
    orderSpy: jasmine.Spy;
    routerSpy: jasmine.Spy;
    title: HTMLElement;

    constructor() {
      const orderService = fixture.debugElement.injector.get(OrderService);
      this.orderSpy = spyOn(orderService, 'getOrder').and.returnValue(Observable.of(fakeOrder));
    }
  }

  function createComponent() {
    fixture = TestBed.createComponent(OrderDetailComponent);
    page = new Page();

    fixture.detectChanges();

    return fixture.whenStable().then(() => {
      fixture.detectChanges();
    });
  }

  beforeEach(() => {
    activatedRoute = new ActivatedRouteStub();
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [OrderDetailComponent],
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [
        OrderService,
        {provide: ActivatedRoute, useValue: activatedRoute},
        {provide: Router, useClass: RouterStub},
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  }));

  describe('when navigate with existing id', () => {
    beforeEach(async(() => {
      activatedRoute.testParamMap = {id: fakeOrder.id};
      createComponent();
    }));

    it('should show title', () => {
      expect(page.orderSpy).toHaveBeenCalledWith(fakeOrder.id);
    });
  });

});

但我不断收到此错误:TypeError: Cannot read property 'subscribe' of undefined

我从 Agular 文档中获取了 ActivatedRouteStub 和测试结构:https://angular.io/guide/testing

组件的代码可以很好地处理来自后端的真实数据并显示订单。

我的代码库也包含类似的测试,它成功地在另一个具有类似服务的组件上做同样的事情,所以这个测试是唯一失败的地方。

使用 Angular 4.3.6、Karma 1.7.1 和 Jasmine 2.6.4。

可能出现什么问题以及如何消除此错误?

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    经过一番研究,我实际上弄清楚了导致错误的原因。我删除了

    {provide: Router, useClass: RouterStub},
    

    并且错误消失了。没有这个存根,测试现在可以正常工作。

    不确定是什么问题,但我认为文档中的RouterStub 类缺少一些必要的实现。课程取自这里:

    https://angular.io/guide/testing#test-a-routed-component

    https://angular.io/generated/live-examples/testing/app-specs.eplnkr.html

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 2019-04-06
      • 2018-11-11
      • 2019-08-06
      • 1970-01-01
      • 2018-02-13
      • 2017-06-28
      • 2019-08-22
      • 1970-01-01
      相关资源
      最近更新 更多