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. CF85E Guard Towers(二分答案+二分图)

    题意 已知 N 座塔的坐标,N≤5000 把它们分成两组,使得同组内的两座塔的曼哈顿距离最大值最小 在此前提下求出有多少种分组方案 mod 109+7 题解 二分答案 mid 曼哈顿距离 >mi ...

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

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

  3. hdu 思维风暴

    点击打开链接 偶然在杭电上看到的题目,数学题.好像是一道六年级奥赛题目,反正我是没有想出来,也知道往那上面想.就是找不到规律啊.学习了网上的方法, 这道题须要求出来多添加的点,就是与之前每条边添加的点 ...

  4. [Java][log4j]支持同一时候按日期和文件大小切割日志

    依据DailyRollingFileAppender和RollingFileAppender改编,支持按日期和文件大小切割日志.  源文件: package com.bao.logging; impo ...

  5. 洛谷P4051 [JSOI2007]字符加密

    题目描述 喜欢钻研问题的JS 同学,最近又迷上了对加密方法的思考.一天,他突然想出了一种他认为是终极的加密办法:把需要加密的信息排成一圈,显然,它们有很多种不同的读法. 例如‘JSOI07’,可以读作 ...

  6. org.xml.sax.SAXParseException: Content is not allowed in prolog

    sax错误:org.xml.sax.SAXParseException: Content is not allowed in prolog解决  标签: org. xml. sax. saxparse ...

  7. win7系统 连接打印机 提示 “正在检查 windows update 需要一段时间”

    现象:  在客户端 添加 打印机时,出现  “网络安装打印机 一直在检查 windows update”  提示 处理:等待上述提示结束后,会出现手动添加 提示窗口,在框内选择打印机驱动 .

  8. WISP > Client+AP > WDS  的区别

    最直白易懂的分别:WISP > Client+AP > WDS WISP,真正万能,兼容任何厂牌的上级AP,毋须设置上级AP,不受上级AP的信道影响,自由DHCP,所带机器或设备的IP,上 ...

  9. 学习《TensorFlow实战Google深度学习框架 (第2版) 》中文PDF和代码

    TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用.<TensorFlow:实战Google深度学习框架(第2版)>为TensorFlow入门参考书,帮助快速. ...

  10. shell脚本的if判断语句

    if条件判断语句 if (表达式) #if ( Variable in Array ) 语句1 else 语句2 fi 1.测试数字大小 #!/bin/sh NUM=100 if (( $NUM &g ...