在过去的两天中,我使用Angular 6尝试了许多不同的方法,本文的最新方法是:https : //stackoverflow.com/a/47401544。但是,仍未根据请求设置标头。
import {Inject, Injectable} from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do((event: HttpEvent<any>) => {
if (localStorage.getItem('id_token') != null) {
// Clone the request to add the new header.
const request = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
'Authorization': `Bearer ${localStorage.getItem('id_token')}`
}
});
return …Run Code Online (Sandbox Code Playgroud) 我需要下载 CSV 并在 Protractor 测试中检查其内容。测试作为我们部署过程的一部分运行,因此此下载的路径需要是相对的。
查看其他解决方案,我在 /e2e 创建了一个名为 download 的文件夹并将其添加到我的protractor.conf.js:
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--disable-gpu']
},
prefs: {
'download': {
'prompt_for_download': false,
'default_directory': '/e2e/download'
}
}
},
Run Code Online (Sandbox Code Playgroud)
这是原始测试,单击按钮下载文件,然后检查本地下载文件夹中的内容(下载本身实际运行后需要更改)。
it('should export the csv', () => {
const filename = '../../../Downloads/new_Name_List_members.csv';
const exportButton = testUI.findElementBy({findBy: 'buttonText', value: 'Export to CSV'});
exportButton.click().then(() => {
browser.driver.wait(function() {
// Wait until the file has been downloaded.
return fs.existsSync(filename);
}, 5000).then(function() {
expect(fs.readFileSync(filename, { encoding: 'utf8' })).toContain('username,email,name');
});
}); …Run Code Online (Sandbox Code Playgroud) 如标题所示,我需要router.events在单元测试中进行模拟。
在我的组件中,我做了一些正则表达式来获取url中斜线之间的文本的第一个实例;例如,/pdp/
constructor(
private route: ActivatedRoute,
private router: Router,
}
this.router.events.pipe(takeUntil(this.ngUnsubscribe$))
.subscribe(route => {
if (route instanceof NavigationEnd) {
// debugger
this.projectType = route.url.match(/[a-z-]+/)[0];
}
});
Run Code Online (Sandbox Code Playgroud)
构建组件时,我的单元测试出错误:Cannot read property '0' of null。当我在调试器中添加注释时,route似乎没有正确设置,但是我在单元测试中对其进行了设置。我已经通过几种不同的方式完成了此工作(受本篇文章的启发:模拟router.events.subscribe()Angular2等)。
第一次尝试:
providers: [
{
provide: Router,
useValue: {
events: of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit'))
}
},
// ActivatedRoute also being mocked
{
provide: ActivatedRoute,
useValue: {
snapshot: { url: [{ path: 'new' }, { path: 'edit' }] },
parent: { …Run Code Online (Sandbox Code Playgroud)