首页 > 解决方案 > 无法在角度单元测试中模拟服务并返回数据 - 未定义

问题描述

我有以下组件,我正在尝试为其编写单元测试。当我运行以下测试时,我看到了

console.log('**fav**' + favorite[`isFavorite`]);

因为undefined我认为我试图通过模拟服务返回的数据没有被返回。我的理解是,为了测试它,我应该模拟服务并返回数据,然后调用handleData并执行。我犯的错误在哪里?

  ngOnInit(): void {
    this.favoriteService.getData().subscribe(item => {
      if (Object.keys(item).length) {
        this.handleData(item);
      }
    });
  }

  handleData(favorite) {
    console.log('**fav**' + favorite[`isFavorite`]);
    if (favorite[`isFavorite`]) {
      console.log('****1****');
      // some logic
    } else {
      // some logic
    }
  }

以下是我的规格文件 -

describe('FavoritesComponent', () => {
  let component: FavoritesComponent;
  let fixture: ComponentFixture<FavoritesComponent>;
  let stubFavoriteGatewaySpec: StubFavoriteGatewaySpec;
  let spyFavoriteService: jasmine.SpyObj<FavoriteService>;

  const favouriteData = [
    {
      tickerTypeName: 'Market Price',
      type: 'MP',
      headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      data: [
        [1, '1.020'],
        [0, '-0.250'],
        [-5, '-4.560'],
        [-149, '-149.000'],
      ],
      isFavorite: true,
    }
  ];

  beforeEach(async(() => {
    stubFavoriteGatewaySpec = new StubFavoriteGatewaySpec();
    spyFavoriteService = jasmine.createSpyObj('FavoriteService', [
      'getData',
    ]);
    spyFavoriteService.getData.and.returnValues(of(favouriteData));

    TestBed.configureTestingModule({
      imports: [MatExpansionModule],
      declarations: [FavoritesComponent],
      providers: [
        { provide: FavoritesGateway, useValue: stubFavoriteGatewaySpec },
        { provide: FavoriteService, useValue: spyFavoriteService },
      ],
    })
      .compileComponents()
      .catch(console.log);
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(FavoritesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

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

标签: angulartypescript

解决方案


//嘲笑

const favouriteData = {
  tickerTypeName: 'Market Price',
  type: 'MP',
  headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
  data: [
    [1, '1.020'],
    [0, '-0.250'],
    [-5, '-4.560'],
    [-149, '-149.000'],
  ],
  isFavorite: true,
};

//测试

it(
'should set the favorite to true onload',
fakeAsync(() => {
  spyOn(spyFavoriteService, 'getData').and.returnValue(of(favouriteData));
  component.ngOnInit();
  expect(component.isFavorite).toBeTruthy();
 //test your other logic 
})
);

无需监视beforeEach,在测试级别模拟它。不确定您要在句柄函数中执行什么操作,如果您有这样的组件变量,isFavorite那么它应该可以工作。

如果使用 Angular 12 使用waitForAync而不是fakeAsync.


推荐阅读