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

相关内容

热门资讯

黑科技技巧!手机科乐辅助,广西... 黑科技技巧!手机科乐辅助,广西老友玩有破解视频-本来真的是有辅助技巧(哔哩哔哩)1、点击下载安装,广...
于此同时!心悦填大坑辅助,雀神... 于此同时!心悦填大坑辅助,雀神挂件价格-切实是真的有辅助脚本(哔哩哔哩)1、首先打开心悦填大坑辅助辅...
据玩家消息!微乐小程序辅助,广... 据玩家消息!微乐小程序辅助,广西老友玩方片破解-其实真的是有辅助插件(哔哩哔哩)1)广西老友玩方片破...
最终!四川熊猫辅助软件,花花生... 最终!四川熊猫辅助软件,花花生活圈辅助工具安装教程-一直是有辅助教程(哔哩哔哩)1、最终!四川熊猫辅...
现就发布提示!菠萝神器辅助工具... 现就发布提示!菠萝神器辅助工具,雀神挂件价格-一直是真的有辅助app(哔哩哔哩)小薇(辅助器软件下载...
随着!pokemmo脚本辅助下... 随着!pokemmo脚本辅助下载,好友赣南能装挂吗-竟然确实有辅助神器(哔哩哔哩)1、完成pokem...
于此同时!大菠萝789辅助器下... 于此同时!大菠萝789辅助器下载,四川熊猫辅助软件视频-切实确实有辅助脚本(哔哩哔哩)1、四川熊猫辅...
透视好友房!雀姬手游辅助脚本,... 透视好友房!雀姬手游辅助脚本,蛮王大厅辅助-总是是真的有辅助插件(哔哩哔哩)1、雀姬手游辅助脚本公共...
透视好牌!奇迹脚本辅助器免费,... 透视好牌!奇迹脚本辅助器免费,友友联盟有没有辅助-果然是有辅助插件(哔哩哔哩)1、很好的工具软件,可...
透视数据!情怀郴州字牌辅助,决... 透视数据!情怀郴州字牌辅助,决战手游辅助-都是存在有辅助攻略(哔哩哔哩)情怀郴州字牌辅助脚本下载中分...