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. Linux 中常用的基础命令一

    1.目录相关命令的使用  pwd(printing working directory) 显示当前工作目录    pwd命令相关的环境变量:     PWD  保存了当前工作目录路径     OLDP ...

  2. 【J-meter】正则表达式提取

    当获取的值中含有折行,可采用下面的办法解决:

  3. 【Henu ACM Round#19 E】 Om Nom and Candies

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 紫书上的原题: 链接 [代码] #include <bits/stdc++.h> #define ll long lon ...

  4. android 选取部分 log 的两种方法

    Grep多个条件: android logcat -v time | grep -e A -e B 选取多个android log tag: android logcat -v time -s TAG ...

  5. Android——4.2 - 3G移植之路之 APN (五)

    APN,这东西对于刚接触的人来说并非那么好理解.对于3G移植上网不可缺少,这里记录一下. 撰写不易,转载请注明出处:http://blog.csdn.net/jscese/article/detail ...

  6. Unity 之 C# 利用回调函数实现C++匿名函数

    做C++开发的都用过匿名函数很好用,可是C#开发怎么实现呢?前几天做一个拍照功能的时候.我偶然发现某个函数假设是C++的话.用匿名函数太好了,于是開始研究C#的回调,代理.托付等,最后总算是实现了我想 ...

  7. Android禁止ViewPager的左右滑动

    转载请注明出处:http://blog.csdn.net/allen315410/article/details/40744287 有时候在开发中会遇到一些"诡异"的要求,比方在V ...

  8. shell 脚本去掉月份和天数的前导零

    #!/bin/sh # # shell 脚本去掉月份和天数的前导零 # 前面填 1 变成百位数,然后减 100 # 去掉前导零的通用方法 $((10#$(date +%m))) # 把字符串分割成数组 ...

  9. LSTM入门学习——本质上就是比RNN的隐藏层公式稍微复杂了一点点而已

    LSTM入门学习 摘自:http://blog.csdn.net/hjimce/article/details/51234311 下面先给出LSTM的网络结构图: 看到网络结构图好像很复杂的样子,其实 ...

  10. BZOJ 4003 左偏树

    思路: 用到了左偏树合并复杂度是logn的性质 一开始先BFS一遍 打标记的左偏树 //By SiriusRen #include <cstdio> #include <cstrin ...