Angular Jasmine测试在ngOnInit中不触发订阅。
创始人
2024-10-19 08:30:04
0

要解决Angular Jasmine测试中ngOnInit不触发订阅的问题,可以使用SpyOn方法来模拟订阅并进行测试。下面是一个示例代码:

组件代码:

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-my-component',
  template: `
{{ data }}
` }) export class MyComponent implements OnInit { data: string; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.getData().subscribe(res => { this.data = res; }); } }

数据服务代码:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable()
export class DataService {
  getData(): Observable {
    return of('Hello World');
  }
}

测试代码:

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

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

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

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

  it('should subscribe to dataService', () => {
    // 创建一个可观察对象模拟返回的数据
    const data = of('Test Data');

    // 使用SpyOn方法模拟getData方法并返回模拟数据
    spyOn(dataService, 'getData').and.returnValue(data);

    // 手动调用ngOnInit方法
    component.ngOnInit();

    // 断言数据是否正确设置
    expect(component.data).toEqual('Test Data');
  });
});

在这个示例中,我们使用SpyOn方法来模拟DataService中的getData方法,并返回一个可观察对象。然后,我们手动调用ngOnInit方法,并断言数据是否正确设置。这样就可以测试ngOnInit中的订阅行为了。

相关内容

热门资讯

最终!哈糖大菠萝怎么开挂(透视... 最终!哈糖大菠萝怎么开挂(透视)丽水都莱破解器(切实有辅助工具)-哔哩哔哩1、每一步都需要思考,不同...
透视攻略!竞技联盟破解版最新版... 透视攻略!竞技联盟破解版最新版(透视)pokemmo辅助脚本(辅助)本来是真的有脚本(哔哩哔哩)1、...
于此同时!wepoker透视辅... 于此同时!wepoker透视辅助下载(透视)玖游卡五星辅助(竟然是真的辅助工具)-哔哩哔哩1、下载好...
透视妙招!约局吧开挂(透视)哈... 透视妙招!约局吧开挂(透视)哈糖大菠萝开挂(辅助)总是真的有攻略(哔哩哔哩)1、让任何用户在无需哈糖...
透视科技!we-poker正规... 透视科技!we-poker正规吗(透视)微信小程序微乐辅助器教程(总是存在有辅助插件)-哔哩哔哩1、...
透视步骤!德州来玩辅助器(透视... 透视步骤!德州来玩辅助器(透视)pokemmo手机版脚本(辅助)原来真的有app(哔哩哔哩)1、po...
透视ai代打!如何下载德普之星... 透视ai代打!如何下载德普之星辅助软件(透视)微信小程序万能修改器(原来是真的辅助插件)-哔哩哔哩微...
透视模块!德州局透视脚本免费版... 透视模块!德州局透视脚本免费版下载手机版(透视)uupoker透视(辅助)一贯真的是有脚本(哔哩哔哩...
目前!wepoker私人局辅助... 目前!wepoker私人局辅助挂(透视)天酷大厅辅助(切实有辅助工具)-哔哩哔哩天酷大厅辅助是不是有...
透视攻略!来玩app破解(透视... 透视攻略!来玩app破解(透视)约局吧怎么看有没有挂(辅助)切实真的有神器(哔哩哔哩)1、玩家可以在...