Angular单元测试中,Observable的mock/spy在第一次调用成功后,在第二次调用时失败。
创始人
2024-10-23 22:30:40
0

问题通常是由于Observable的内部状态没有正确重置所导致的。为了解决这个问题,可以使用jasmine的beforeEach钩子,在每个测试之前重置Observable的内部状态。

示例代码:

import { of } from 'rxjs';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('should call getData() twice and return correct values', () => {
    // mock the observable
    spyOn(component.myService, 'getData').and.returnValue(
      of([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }])
    );

    // first call
    component.getData();
    expect(component.data).toEqual([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]);

    // reset the internal state of the observable
    spyOn(component.myService, 'getData').and.returnValue(
      of([{ id: 3, name: 'Bob' }, { id: 4, name: 'Alice' }])
    );

    // second call
    component.getData();
    expect(component.data).toEqual([{ id: 3, name: 'Bob' }, { id: 4, name: 'Alice' }]);
  });
});

在这个示例中,beforeEach钩子会在每个测试运行之前创建组件和测试环境。在it测试中,我们首先使用spyOn对服务中的getData方法进行了mock,并在第一次调用getData后对component.data的值进行了断言。然后,我们使用相同的方法重置了getData,并在第二次调用getData后对component.data

相关内容

热门资讯

有挂方略辅助!wepoker辅... wepoker辅助器是一款专注玩家量身打造的游戏记牌类型软件,在wepoker辅助器这款游戏中我们可...
有人有挂开挂!四川途游辅助软件... 有人有挂开挂!四川途游辅助软件瞎子啊,边锋老友内蒙古辅助(透视好牌开挂辅助软件)>>您好:软件加薇1...
竟然有挂开挂!四川熊猫辅助软件... 竟然有挂开挂!四川熊猫辅助软件,潮汕掌上娱破解(玩家攻略开挂辅助工具);四川熊猫辅助软件免费下载原版...
有挂解惑辅助!拼三张辅助器,陕... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
有挂存在辅助!微乐小程序辅助器... 有挂存在辅助!微乐小程序辅助器脚本,新道游正版辅助(交流学习经验开挂辅助软件)>>您好:软件加薇13...
有挂猫腻开挂!多乐游戏小程序辅... 有挂猫腻开挂!多乐游戏小程序辅助,微乐家乡自建房辅助app(一起来探讨开挂辅助工具);无需打开直接搜...
真是有挂辅助!手机脚本辅助软件... 手机脚本辅助软件是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微...
有挂方法开挂!朋朋政和麻将为什... 朋朋政和麻将为什么一直输是一款专注玩家量身打造的游戏记牌类型软件,在朋朋政和麻将为什么一直输这款游戏...
有挂攻略开挂!老友广东麻将有没... 有挂攻略开挂!老友广东麻将有没有假,来物局潮汕辅助(透视智能ai开挂辅助安装) 【无需打开直接搜索加...
有挂总结辅助!宝宝浙江辅助工具... 有挂总结辅助!宝宝浙江辅助工具,永胜联盟金花辅助(玩家必看分享开挂辅助软件);无需打开直接搜索打开薇...