Blog>
Snippets

Unit Testing CSRF Protection Logic in Angular

Showcase a test case that verifies CSRF protection logic in an Angular service using the TestBed utility.
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpXsrfTokenExtractor } from '@angular/common/http';
import { MyService } from './my.service';

describe('CSRF Protection Logic', () => {
  let httpTestingController: HttpTestingController;
  let service: MyService;
  let xsrfTokenExtractor: HttpXsrfTokenExtractor;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [MyService, {provide: HttpXsrfTokenExtractor, useValue: {getToken: () => 'dummy-csrf-token'}}]
    });
    httpTestingController = TestBed.inject(HttpTestingController);
    service = TestBed.inject(MyService);
    xsrfTokenExtractor = TestBed.inject(HttpXsrfTokenExtractor);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should have CSRF token in header when posting', () => {
    const testUrl = '/api/test';
    const testData = { payload: 'data' };

    service.postData(testUrl, testData).subscribe(response => {
      expect(response).toBeTruthy();
    });

    const req = httpTestingController.expectOne(testUrl);
    expect(req.request.method).toBe('POST');
    expect(req.request.headers.get('X-XSRF-TOKEN')).toBe('dummy-csrf-token');
    req.flush({});
  });
});
This JavaScript code snippet defines a Jasmine test suite that uses Angular TestBed to test if an Angular service correctly sets the CSRF token in the header of a POST request. It mocks the `HttpXsrfTokenExtractor` to return a dummy CSRF token and verifies if the token is included in the headers of the request sent by `MyService`.