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 元素中获取服务,相比之下更加灵活。无论使用那种方式获取服务,我们都可以写出有效的单元测试。

相关内容

热门资讯

辅助透视!wpk透视辅助下载,... 辅助透视!wpk透视辅助下载,hhpoker作弊实战视频,分享教程(有挂方法)1、hhpoker作弊...
透视辅助!wepoker破解是... 透视辅助!wepoker破解是真的还是假的,wepoker模拟器哪个(透视)必胜教程(有挂揭秘)1、...
透视存在!wepoker透视脚... 透视存在!wepoker透视脚本免费app,wpk俱乐部辅助器,微扑克教程(有挂秘籍)1、每一步都需...
透视能赢!wepoker轻量版... 透视能赢!wepoker轻量版透视方法,wepoker-h5下载(透视)教你攻略(有挂解说);1、透...
透视科技!线上德州的辅助器是什... 透视科技!线上德州的辅助器是什么,wepokerplus万能挂,科技教程(有挂详情)线上德州的辅助器...
透视好友!wejoker免费脚... 透视好友!wejoker免费脚本,we-poker辅助器(透视)wpk教程(有挂揭秘);1、进入游戏...
透视代打!hhpoker透视脚... 透视代打!hhpoker透视脚本,wejoker手机版透视脚本,必赢方法(有挂秘笈)1、下载好wej...
透视新版!wepoker轻量版... 透视新版!wepoker轻量版透视,wepoker透视苹果系统(透视)必赢教程(有挂技巧)1、玩家可...
透视中牌率!wpk真的有透视嘛... 透视中牌率!wpk真的有透视嘛,wepokerplus透视脚本免费,2025新版技巧(有挂规律);1...
透视透视!wepoker好友房... 透视透视!wepoker好友房开挂,wepoker软件辅助程序(透视)力荐教程(有挂教程);1、起透...