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

相关内容

热门资讯

一分钟揭秘!扑克之星辅助,we... 一分钟揭秘!扑克之星辅助,wepoker透视脚本免费下载,爆料教程(有挂透明);玩家必备必赢加哟《1...
透视系统!wepoker破解器... 透视系统!wepoker破解器(透视)总是是有挂(详细辅助细节揭秘)1、ai辅助优化,发牌逻辑科技护...
一分钟秒懂!哈糖大菠萝辅助器,... 一分钟秒懂!哈糖大菠萝辅助器,hhpoker破解工具,2025版教程(有挂方法);支持2-10人实时...
透视免费!德州真人透视脚本(透... 透视免费!德州真人透视脚本(透视)一贯真的有挂(详细辅助爆料教程)1、这是跨平台的黑科技,在线的操作...
玩家必看教程!wepoker私... 玩家必看教程!wepoker私人局俱乐部怎么进,佛手在线大菠萝智能辅助器,透视教程(有挂技巧)准备好...
透视教程!菠萝德州透视脚本(透... 透视教程!菠萝德州透视脚本(透视)确实真的有挂(详细辅助详细教程)1、机器人多个强度级别选择2、发牌...
一分钟秒懂!wepoker辅助... 1、一分钟秒懂!wepoker辅助器安装包,wepoker辅助器安装包,wpk教程(有挂攻略);详细...
透视线上!wepoker脚本(... 透视线上!wepoker脚本(透视)一贯是真的有挂(详细辅助攻略教程);wepoker脚本是一种具有...
关于!wepoker游戏下载,... 1、关于!wepoker游戏下载,aapoker破解侠是真的吗,可靠技巧(有挂软件)(UU poke...
透视软件!wepoker底牌透... 透视软件!wepoker底牌透视(透视)好像存在有挂(详细辅助细节揭秘)1、每一步都需要思考,不同水...