首页 > 解决方案 > 如何对来自activatedRoute的oninit数据是否可用进行单元测试

问题描述

我是 angular 单元测试的新手。我们正在使用 jest 并且真的不知道如何测试路由是否正在返回数据。我想知道我们是否可以进行单元测试以检查数据是否以角度从路线返回。非常感谢任何帮助

在我的课上 component.ts

public data$: Observable<Data>;
  public salariesPerHours: salariesPerHoursViewModel[];

  private destroy$ = new Subject<boolean>();

  constructor(private activatedRoute: ActivatedRoute) {}

  public ngOnInit(): void {

    this.data$ = this.activatedRoute.data;
    this.data$?.pipe(takeUntil(this.destroy$)).subscribe((data: Data) => {
      this.salariesPerHours= data?.Salary?.salaryPerHour;
    });
  }

在测试类组件中

import { ActivatedRoute, Data } from '@angular/router';
import { salariesPerHoursViewModel,SalaryType } from 'lib/store/store.barrel';
import { Subject } from 'rxjs';

import { SalaryComponent } from './salary.component';

const dataMock: salariesPerHoursViewModel[] = [
  {
      year:2018,
      salaryModifications:[
         {
            date:'2018-02-01T00:00:00',
            type: 'Salary',
            action:[
               {
                  logical :'0212834',
                  label:''
               }
            ]
         },
        ]
  }
]


describe('SalaryComponent', () => {
  let component: SalaryComponent;
  let activatedRoute: ActivatedRoute;

  beforeEach(() => {
    activatedRoute = new ActivatedRoute();
    component = new SalaryComponent(activatedRoute);
  });

  describe('ngOnInit', () => {
    beforeEach(() => {
      jest.spyOn(component, 'ngOnInit');
    });
   //how to  test if data is coming up
   
  });

  describe('ngOnDestroy', () => {
    test('should complete the destroy observable', () => {
      component['destroy$'].next = jest.fn();
      component['destroy$'].complete = jest.fn();

      component.ngOnDestroy();

      expect(component['destroy$'].next).toHaveBeenCalledWith(true);
      expect(component['destroy$'].complete).toHaveBeenCalled();
    });
  });
});

标签: angulartypescriptunit-testingrxjsjestjs

解决方案


在 ngOnInit 内部使用了activatedRoute,因此后者不是被监视而是直接测试。

现在,你的输入和输出是什么?this.activatedRoute.data 是输入,this.salariesPerHours 是输出。

因此,在调用 ngOnInit 之前,您应该设置输入:

this.activatedRoute.data = of(<mock containing Salary.salaryPerHour>);

并且,在调用 ngOnInit 之后,您应该检查 this.salariesPerHours 与预期值:

expect(this.salariesPerHours).toBe(<Salary.salaryPerHour from mock>);

重要的是要观察 this.activatedRoute.data 分配了一个同步可观察('of' 运算符)以允许在订阅后立即调用回调(分配 this.salariesPerHours),这使得测试可控。


推荐阅读