如何设置Cookie并进行角度测试?

时间:2018-11-28 15:33:19

标签: angular unit-testing cookies jasmine

我想在我的http服务中设置一个cookie,并测试该cookie是否在请求中发送到后端。我应该如何设置Cookie并验证其随请求一起发送?

我相信我的服务正在设置cookie(document.cookie),我希望该消息将在标头中发送。

我的服务:

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SessionService {
  readonly url = 'http://www.bs.com';
  constructor(private httpClient: HttpClient) { }

  getBS(): Observable<any> {
    document.cookie = 'username=John Doe';
    return this.httpClient.get(this.url);
 }
}

我的测试代码:

import { TestBed} from '@angular/core/testing';
import { SessionService } from './session.service';
import {HttpClientTestingModule, HttpTestingController} from '../../node_modules/@angular/common/http/testing';
import {Injector} from '@angular/core';

describe('SessionService', () => {
  let injector: Injector;
  let exampleService: SessionService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    injector = TestBed.configureTestingModule({
    imports: [
      HttpClientTestingModule
    ],
    providers: [
     SessionService
    ]
  });
  exampleService = injector.get(SessionService);
  httpMock = injector.get(HttpTestingController);
});

 it('should be created', () => {
   const test = 'hello world from server!';

   exampleService.getBS().subscribe(str => {
    expect(str).toBe(test);
   });
   const req = httpMock.expectOne('http://www.bs.com');
   req.flush(test);
});
);
})

0 个答案:

没有答案