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. bzoj 1088 [SCOI2005] 扫雷

    SCOI2005 扫雷 一道很有趣的(水)题 “这道题有四种解法,你知道么” 给你矩阵的第二列的数字,求出第一列雷有多少种可能的摆法. 不懂扫雷规则的自行按win+R然后输入winmine 思考过后我 ...

  2. springMVC+request.session实现用户登录和访问权限控制

    用springmvc mybatis实现用户登录登出功能,使用session保持登录状态,并实现禁止未登录的用户访问.感谢谷歌资源,在这里做个学习记录加深自己的印象. 原文在我的https://my. ...

  3. updatedb---创建或更新slocate命令所必需的数据库文件

    updatedb命令用来创建或更新slocate命令所必需的数据库文件.updatedb命令的执行过程较长,因为在执行时它会遍历整个系统的目录树,并将所有的文件信息写入slocate数据库文件中. 补 ...

  4. cocos2d-x 学习资源整理(持续更新...)

    生活像一把无情刻刀.改变了我们模样.以前我以为会亘古不变的东西,突然在一瞬间失去了信念... 假设你改变不了生活中患得患失的心情.那就试着让自己变得强大一点.由于能做到不以物喜不以己悲都是建立在强大的 ...

  5. 给一个执行在windows 7和NAT下的VMWARE虚拟机分配固定IP

    虚拟机上装了个oracleserver,每次vmware重新启动或者resume时总要分配新的IP地址,这样就得改动windows下的client配置,所以须要想办法把IP地址固定住. DHCP服务在 ...

  6. HDU Victor and World (最短路+状态压缩)

    题目链接:传送门 题意: n个城市m条路.刚開始在点1,求把每一个城市都遍历一边最后回到1的花费的最小值. 分析: ​​+n​2​​∗2​n​​). 转自Bestcode. 以下说说我的状态转移,首先 ...

  7. UINavigationBar的系统渲染方式

    昨天想手工实现一下类知乎日报的Navigation Bar的动态颜色改变,但不管怎么设置Navigation Bar的 backgroundColor barTintColor alpha參数都达不到 ...

  8. 离线安装 Chrome

    离线安装 Chrome 在这个帮助网页中最下面切换到中文 https://support.google.com/chrome/answer/95346 在网页的中上部点击 "离线安装 Chr ...

  9. vue10 v-text v-html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. .Net 跳转

    Action正常跳转 <a href="@Url.Action("AppDownload")">点击下载APP</a> public A ...