【问题标题】:How do unit testing on whether data is available oninit from activatedRoute如何对来自activatedRoute的oninit数据是否可用进行单元测试
【发布时间】:2021-03-23 13:05:18
【问题描述】:

我是 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();
    });
  });
});

【问题讨论】:

    标签: angular typescript unit-testing rxjs jestjs


    【解决方案1】:

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

    现在,您的输入和输出是什么? 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),这使得测试可控。

    【讨论】:

    • 很酷,谢谢您的回复。美好的一天
    猜你喜欢
    • 2020-05-28
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2010-09-08
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多