Angular 7单元测试依赖注入在ngOnInit中不起作用。
创始人
2024-10-17 00:30:08
0

在Angular 7中,如果在ngOnInit方法中进行依赖注入的单元测试时出现问题,可能是因为在测试过程中没有正确配置测试环境。以下是一个解决方法的示例:

首先,确保你的组件被正确导入:

import { MyComponent } from './my.component';

然后,在describe块中配置测试环境:

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

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

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

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

在上述代码中,我们使用TestBed来配置测试环境,并使用compileComponents()方法编译组件。然后,我们使用createComponent方法创建组件实例,并进行必要的变更检测。

接下来,我们可以在beforeEach块中设置依赖注入:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { MyService } from './my.service';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [ MyService ] // 添加服务提供商
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    myService = TestBed.get(MyService); // 获取注入的服务实例
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call ngOnInit and inject MyService', () => {
    spyOn(component, 'ngOnInit').and.callThrough();
    expect(component.ngOnInit).toHaveBeenCalled();
    expect(myService).toBeTruthy();
  });
});

在上述代码中,我们首先在providers数组中添加MyService,以便在组件实例化时注入该服务。然后,我们使用TestBed的get方法获取MyService实例,并将其存储在myService变量中。

接下来,在it块中,我们使用spyOn方法来监视ngOnInit方法,并验证它是否被调用。我们还验证myService是否成功注入。

这样,我们就可以在ngOnInit方法中进行依赖注入的单元测试了。

相关内容

热门资讯

第1分钟辅助!闲来辅助神器下载... 第1分钟辅助!闲来辅助神器下载2022,本来是真的有辅助器(有挂工具)1、闲来辅助神器下载2022辅...
5分钟辅助!奇迹手游辅助,好像... 5分钟辅助!奇迹手游辅助,好像是真的有辅助app(有挂教学)1、很好的工具软件,可以解锁游戏的奇迹手...
第七分钟辅助!顺欣茶楼软件,原... 第七分钟辅助!顺欣茶楼软件,原来真的是有辅助神器(果真有挂)顺欣茶楼软件能透视中分为三种模型:顺欣茶...
十分钟辅助!微信链接透视脚本下... 十分钟辅助!微信链接透视脚本下载,一直存在有辅助技巧(有挂攻略)1、金币登录送、破产送、升级送、活动...
8分钟辅助!衢州都莱辅助工具定... 8分钟辅助!衢州都莱辅助工具定制开发,一直真的是有辅助方法(有挂方式)1、衢州都莱辅助工具定制开发辅...
第六分钟辅助!科乐天天踢解码器... 第六分钟辅助!科乐天天踢解码器,一直是有辅助脚本(有挂技术)1、完成科乐天天踢解码器有辅助插件,帮助...
2分钟辅助!微信小程序多功能辅... 2分钟辅助!微信小程序多功能辅助,一贯是真的有辅助教程(有挂细节)1、下载好微信小程序多功能辅助脚本...
4分钟辅助!河洛杠次怎么提高胜... 4分钟辅助!河洛杠次怎么提高胜率,原来有辅助app(有挂功能)一、河洛杠次怎么提高胜率可以开透视的定...
两分钟辅助!广西八一字牌有挂吗... 两分钟辅助!广西八一字牌有挂吗,确实存在有辅助插件(有挂技巧)小薇(辅助器软件下载)致您一封信;亲爱...
4分钟辅助!传送屋激k万能辅助... 4分钟辅助!传送屋激k万能辅助器app,好像真的有辅助挂(果真有挂)在进入传送屋激k万能辅助器app...