Both what "TestBed.get" & "injector" trying to do is get service for the test component.

But there is some diffenece which determined when use which.

Register the service: 

You need to mock the service, not using the real service!

You can use mock class, or just an object.

userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User'}
};
TestBed.configureTestingModule({
declarations: [ WelcomeComponent ],
// providers: [ UserService ] // NO! Don't provide the real service!
// Provide a test-double instead
providers: [ {provide: UserService, useValue: userServiceStub } ]
});

"Root Injector"

You may be able to get the service from the root injector via TestBed.get. This is easier to remember and less verbose. But it only works when Angular injects the component with the service instance in the test's root injector.

// UserService from the root injector
userService = TestBed.get(UserService);

"Injected service for Component"

// UserService actually injected into the component
userService = fixture.debugElement.injector.get(UserService);

Code Example:

beforeEach(() => {
// stub UserService for test purposes
userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User'}
}; TestBed.configureTestingModule({
declarations: [ WelcomeComponent ],
providers: [ {provide: UserService, useValue: userServiceStub } ]
}); fixture = TestBed.createComponent(WelcomeComponent);
comp = fixture.componentInstance; // UserService from the root injector
userService = TestBed.get(UserService); // get the "welcome" element by CSS selector (e.g., by class name)
de = fixture.debugElement.query(By.css('.welcome'));
el = de.nativeElement;
}); it('should welcome the user', () => {
fixture.detectChanges();
const content = el.textContent;
expect(content).toContain('Welcome', '"Welcome ..."');
expect(content).toContain('Test User', 'expected name');
}); it('should welcome "Bubba"', () => {
userService.user.name = 'Bubba'; // welcome message hasn't been shown yet
fixture.detectChanges();
expect(el.textContent).toContain('Bubba');
}); it('should request login if not logged in', () => {
userService.isLoggedIn = false; // welcome message hasn't been shown yet
fixture.detectChanges();
const content = el.textContent;
expect(content).not.toContain('Welcome', 'not welcomed');
expect(content).toMatch(/log in/i, '"log in"');
});

[Angular & Unit Testing] TestBed.get vs Injector的更多相关文章

  1. [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests

    In a proper unit test we want to isolate external dependencies as much as possible to guarantee a re ...

  2. [Angular & Unit Testing] Automatic change detection

    When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...

  3. [Angular & Unit Testing] Testing Component with Store

    When using Ngrx, we need to know how to test the component which has Router injected. Component: imp ...

  4. [Angular Unit Testing] Debug unit testing -- component rendering

    If sometime you want to log out the comonent html to see whether the html render correctly, you can ...

  5. [Angular Unit Testing] Testing Component methods

    import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...

  6. [Angular Unit Testing] Testing Services with dependencies

    import { Http, Response, ResponseOptions } from '@angular/http'; import { TestBed } from '@angular/c ...

  7. [Angular Unit Testing] Shallow Pipe Testing

    import { TestBed, ComponentFixture } from '@angular/core/testing'; import { BrowserDynamicTestingMod ...

  8. [Angular & Unit Testing] Testing a RouterOutlet component

    The way to test router componet needs a little bit setup, first we need to create a "router-stu ...

  9. [Unit Testing] Angular Unit Testing, ui-router, httpbackend and spy

    // backend test beforeEach(inject(function (_$compile_, _$httpBackend_, _$rootScope_, _$state_, _Ann ...

随机推荐

  1. Python安装selenium启动浏览器

    1:在Python运行火狐或谷歌的浏览器是需要下载相对应的驱动 例如:你想在Python中使用代码命令打开firefox的网页 如果没有安装驱动,直接运行的话会出下面的错误 所以我们要安装相对应的浏览 ...

  2. EXPIREAT

    EXPIREAT key timestamp EXPIREAT 的作用和EXPIRE类似,都用于为key设置生存时间. 不同在于EXPIREAT命令接受都时间参数是UNIX时间戳(unix times ...

  3. 【转】[译]理解HTTP/304响应

    [转][译]理解HTTP/304响应 原文:http://www.telerik.com/automated-testing-tools/blog/eric-lawrence/12-11-06/und ...

  4. 四 HBase 客户端设置缓存优化查询。

    其实查询无非是一个 HBase 的 RPC 计算公式 .然后给API 提供值. RPCs = (Rows * Cols per Row) / Min(Cols per Row, Batch Size) ...

  5. oracle job有定时执行功能

    oracle job有定时执行的功能,可以在指定的时间点或每天的某个时间点自行执行任务.   oracle job有定时执行的功能,可以在指定的时间点或每天的某个时间点自行执行任务. 一.查询系统中的 ...

  6. Entity Framework之Model First开发方式

    一.Model First开发方式 在项目一开始,就没用数据库时,可以借助EF设计模型,然后根据模型同步完成数据库中表的创建,这就是Model First开发方式.总结一点就是,现有模型再有表. 二. ...

  7. drbd脑裂

    环境: Primary    节点:node1Secondary  节点:node2 DRBD产生脑裂的原因:    (1. 采用HA环境的时候自动切换导致脑裂;    (2. 人为操作或配置失误,导 ...

  8. Conventions and patterns for multi-platform development

    For Developers‎ > ‎Design Documents‎ > ‎ Conventions and patterns for multi-platform developme ...

  9. JAVA学习(一)——基本语法

    tips:前端开发写惯了弱类型语言,再来学强类型语言,真的是被各种修饰符.类型声明给整的云里雾里,而且java语法和javascript语言差别还是很大的,所以做好笔记,把一些需要注意的地方记下来是非 ...

  10. file---探测给定文件的类型

    file命令用来探测给定文件的类型.file命令对文件的检查分为文件系统.魔法幻数检查和语言检查3个过程. 语法 file(选项)(参数) 选项 -b:列出辨识结果时,不显示文件名称: -c:详细显示 ...