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方法中进行依赖注入的单元测试了。

相关内容

热门资讯

一分钟揭秘!wepoker私人... 一分钟揭秘!wepoker私人局外卦,wepoker安装教程,安装教程(有挂教程);支持2-10人实...
记者发布!wepoker线上大... 记者发布!wepoker线上大神,wpk俱乐部辅助器,第三方教程(有挂辅助);科技安装教程;1367...
一分钟揭秘!wejoker辅助... 一分钟揭秘!wejoker辅助软件价格,wejoker辅助机器人,解密教程(有挂辅助);建议优先通过...
技术分享!wepoker辅助器... 自定义wepoker辅助器最新版本更新内容系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微...
推荐几款新版!德州私人局脚本,... 推荐几款新版!德州私人局脚本,wepoker怎么设置盖牌,2025版教程(有挂攻略);科技安装教程;...
总算明白!德州辅助工具到底怎么... 这是一款非常优秀的wepoker私人局辅助器怎么用 ia辅助检测软件,能够让你了解到wepoker私...
六分钟了解!大菠萝免费辅助,w... 六分钟了解!大菠萝免费辅助,wepoker透视器免费,介绍教程(有挂神器);1分钟了解详细教程(微信...
今日百科!hhpoker到底可... 今日百科!hhpoker到底可以作弊吗,impoker辅助,详细教程(有挂攻略);大神普及一款德州a...
一分钟快速了解!xpoker辅... 一分钟快速了解!xpoker辅助怎么用,wepoker钻石怎么看底牌,详细教程(有挂技巧)准备好在w...
一分钟揭秘!wepoker数据... 一分钟揭秘!wepoker数据分析,德普之星透视辅助软件激活码,细节方法(有挂技巧);德普之星透视辅...