[Angular & Unit Testing] TestBed.get vs Injector
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的更多相关文章
- [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 ...
- [Angular & Unit Testing] Automatic change detection
When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...
- [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 ...
- [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 ...
- [Angular Unit Testing] Testing Component methods
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...
- [Angular Unit Testing] Testing Services with dependencies
import { Http, Response, ResponseOptions } from '@angular/http'; import { TestBed } from '@angular/c ...
- [Angular Unit Testing] Shallow Pipe Testing
import { TestBed, ComponentFixture } from '@angular/core/testing'; import { BrowserDynamicTestingMod ...
- [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 ...
- [Unit Testing] Angular Unit Testing, ui-router, httpbackend and spy
// backend test beforeEach(inject(function (_$compile_, _$httpBackend_, _$rootScope_, _$state_, _Ann ...
随机推荐
- mysql主从同步错误恢复
Mysql主从同步集群在生成环境使用过程中,如果主从服务器之间网络通信条件差或者数据库数据量非常大,容易导致MYSQL主从同步延迟. MYSQL主从产生延迟之后,一旦主库宕机,会导致部分数据没有及时同 ...
- Linux学习,部署django项目到服务器,及安装python,uwsgi等
开启网络 vi /etc/sysconfig/network-script/ifcfg-eth0 onboot=yes 退出保存 service network restart ping www.ba ...
- 紫书 习题 10-14 UVa 10886(暴力+数据范围)
开始的时候一看这题感觉很难,觉得肯定有什么很快的办法 不能暴力做(受了上一题10-13的影响) 然后一看那个函数感觉无从下手. 然后看了博客发现,原来这道题就是直接暴力-- 因为n的范围为10的7次方 ...
- 【UVA 437】The Tower of Babylon(记忆化搜索写法)
[题目链接]:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_probl ...
- 洛谷 P3434 [POI2006]KRA-The Disks
P3434 [POI2006]KRA-The Disks 题目描述 For his birthday present little Johnny has received from his paren ...
- django-xadmin使用之更改菜单url
环境:xadmin-for-python3 python3.5.2 django1.9.12 1. 在模块的adminx.py文件中增加以下代码: class AdminSettings(object ...
- 怎样用第三方开源免费软件portecle从https站点上导出SSL的CA证书?
在我这篇文章中.我提到了怎样用OpenSSL从https站点上导出SSL的CA证书? 这样的方式不太直观,且须要用户自己手工拷贝.然后另存为文件,那么有没有更好更方便的工具呢? 幸运的是,有热心于开 ...
- java音乐播放之IO流处理
这个类仅仅能一直播放.知道音乐结束. 比AudioCilp要好一点. import java.io.*; import javax.sound.sampled.*; public class Test ...
- 基于Verilog语言的可维护性设计技术
[注]本文内容主体部分直接翻译参考文献[1]较多内容,因此本文不用于任何商业目的,也不会发表在任何学术刊物上,仅供实验室内部交流和IC设计爱好者交流之用. “曲意而使人喜,不若直节而使人忌:无善而致人 ...
- 6. 使用Axis开发WebService程序
转自:http://www.itkeyword.com/doc/7529577946427268306/Apache-Servlet-WebSOAPWebService 所谓Web Service就是 ...