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. [洛谷P1119][codevs1817]灾后重建

    题目大意:有n个村庄和一些连通两个村庄的双向道路.每个村庄在一个特定的时间修复.没有修复的村庄不能经过.现在有一系列询问,问两个村庄在t时刻的最短路(如果无法到达或两个村庄本身未修复,输出-1). 解 ...

  2. 浅析[分块]qwq

    首先说明这篇博客写得奇差无比 让我们理清一下为什么要打分块,在大部分情况下,线段树啊,splay,treap,主席树什么的都要比分块的效率高得多,但是在出问题的时候如果你和这些数据结构只是混的脸熟的话 ...

  3. COGS——T2084. Asm.Def的基本算法

    http://cogs.pro/cogs/problem/problem.php?pid=2084 ★☆   输入文件:asm_algo.in   输出文件:asm_algo.out   简单对比时间 ...

  4. Android输入法扩展之远程输入法

    近年来,互联网电视開始火热,乐视TV,小米TV,近期爱奇艺也在大肆的招人做爱奇艺电视.当然还有更被关注的苹果电视.事实上,这个趋势非常正常,也非常合理,传统单纯的接收电视节目的电视已经太传统了.是该被 ...

  5. 协变 & 逆变

    都跟里氏替换原则有关. 协变:你可以用一个子类对象去替换相应的一个父类对象,这是完全符合里氏替换原则的,和协(谐)的变.如:用Swan替换Bird. 逆变:你可以用一个父类对象去替换相应的一个子类对象 ...

  6. iPad popView封装

    仿照UITableView的UITableViewDataSource 协义 1.代理.让代理帮我们类完毕一些方法 2.完毕当前类不能完毕的事情还有传值等功能 实现方法 // 1. 声明一个协议 // ...

  7. .net framework tools

    https://docs.microsoft.com/en-us/dotnet/framework/tools/ Resgen.exe (Resource File Generator) Conver ...

  8. Docker -- 2 -- 利用docker部署网站和数据库

    在Docker – 系统整洁之道 – 1中已经对Docker的一些命令和Docker镜像的使用及操作做了记录. 这次就利用docker进行一次真正的实例使用,使用docker搭建一个简单的答题系统,这 ...

  9. && 的用法

    document.body.style.display === "" && (document.body.style.display = "none&qu ...

  10. 动态调用WebService-获取天气

    string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"; string[] args ...