Angular单元测试中Testbed.inject(serviceName)和fixture.debugElement.injector.get(serviceName)有什么区别?
创始人
2024-10-23 22:30:37
0

Testbed.inject() 和 fixture.debugElement.injector.get() 都是通过依赖注入获取服务的方法。不同之处在于,前者是在 TestBed 组件中获取服务,而后者是在测试组件的 debugElement 元素中获取服务。

下面是一个实际的代码示例:

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

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

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

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

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

  it('should inject MyService using Testbed.inject', () => {
    const myService = TestBed.inject(MyService);
    expect(myService).toBeTruthy();
  });

  it('should inject MyService using fixture.debugElement.injector.get', () => {
    const debugElement = fixture.debugElement;
    const myService = debugElement.injector.get(MyService);
    expect(myService).toBeTruthy();
  });
});

从上面的代码中可以看出,Testbed.inject(MyService) 是在 TestBed 组件中直接获取服务,它更加简单和直接。fixture.debugElement.injector.get(MyService) 是在测试组件的 debugElement 元素中获取服务,相比之下更加灵活。无论使用那种方式获取服务,我们都可以写出有效的单元测试。

相关内容

热门资讯

玩家必用!pokemmo辅助脚... 玩家必用!pokemmo辅助脚本,wpk俱乐部是真的吗,竟然真的有挂(有挂实锤)1、完成有辅助插件,...
分辨真假!wepoker有脚本... 分辨真假!wepoker有脚本吗,拱趴大菠萝开挂方法,一贯真的是有挂(存在有挂);1、用户打开应用后...
实测发现!约局吧游戏挂,wej... 实测发现!约局吧游戏挂,wejoker辅助软件,一贯有挂(有挂教学)1、破解器简单,机器人操作,插件...
玩家必看教程!hhpoker辅... 玩家必看教程!hhpoker辅助器视频,wepoker怎么增加运气,其实真的是有挂(真是有挂)1、辅...
程序员教你!werplan外卦... 程序员教你!werplan外卦神器,hhpoker外挂靠谱吗,果然真的有挂(有挂讲解)1、在插件功能...
玩家必看科普!we-poker... 玩家必看科普!we-poker辅助,wepoker轻量版有透视吗,一直存在有挂(有挂方略)1、首先打...
玩家攻略!wepoker亲友圈... 玩家攻略!wepoker亲友圈有用吗,aapoker怎么控制牌,其实存在有挂(有挂技巧)1、点击下载...
一分钟了解!fishpoker... 一分钟了解!fishpoker透视,htx矩阵wepoker辅助,切实是有挂(确实有挂)1、打开软件...
记者发布!约局吧德州透视,cl... 记者发布!约局吧德州透视,cloudpoker外挂,好像是真的有挂(有挂秘诀)1)有没有挂:进一步探...
如何分辨真伪!悟空黑桃a有挂嘛... 如何分辨真伪!悟空黑桃a有挂嘛,wepokerplus开挂,好像真的是有挂(有挂秘笈)1)辅助插件:...