简体   繁体   English

无法在角度单元测试中模拟服务并返回数据 - 表示未定义

[英]Unable to mock a service and return data in angular unit test - says undefined

I have the following component for which I am trying to write a unit tests for.我有以下组件,我正在尝试为其编写单元测试。 When I run the below test, I see value for当我运行下面的测试时,我看到了

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

as undefined meaning the data that I am trying to return by mocking service is not getting returned I think. undefined意味着我想通过模拟服务返回的数据没有被返回。 My understanding is that in order to test it, I should mock the service and return data, which then would call handleData and executes.我的理解是,为了测试它,我应该模拟服务并返回数据,然后调用handleData并执行。 Where is the mistake I am committing?我犯的错误在哪里?

  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
    }
  }

Following is my spec file -以下是我的规范文件 -

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

//Mock //嘲笑

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,
};

//test //测试

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 
})
);

No need to spy on beforeEach , Mock it on test level.无需监视beforeEach ,在测试级别模拟它。 Not sure what you are trying to do inside handle function, if you have a component variable like isFavorite then it should work.不确定您要在 handle 函数中做什么,如果您有像isFavorite这样的组件变量,那么它应该可以工作。

if using Angular 12 use waitForAync instead of fakeAsync .如果使用 Angular 12,请使用waitForAync而不是fakeAsync

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM