Back to Repositories

Testing SCE URL Policy with Base Tags in Angular.js

This test suite evaluates AngularJS’s Strict Contextual Escaping (SCE) URL policy behavior when base tags are present in the document. It verifies URL trust validation across different scenarios including relative paths, absolute URLs, and dynamic base tag modifications.

Test Coverage Overview

The test suite provides comprehensive coverage of URL trust validation scenarios in AngularJS applications with base tags. Key functionality tested includes:

  • Current page URL validation
  • Off-origin URL blocking
  • Relative URL handling
  • Base origin URL validation
  • Dynamic base URL updates

Implementation Analysis

The testing approach uses end-to-end scenarios to validate SCE URL policy enforcement. It employs browser.executeScript() for DOM manipulation and custom helper functions to verify URL trust status. The implementation leverages Jasmine’s describe/it pattern for structured test organization.

Technical Details

Testing tools and configuration:

  • Protractor for e2e testing
  • Jasmine test framework
  • Custom fixture loading mechanism
  • Browser execution context for JavaScript evaluation
  • Helper function (expectToBeTrusted) for URL validation

Best Practices Demonstrated

The test suite demonstrates several testing best practices:

  • Isolated test cases for specific functionality
  • Clear test descriptions
  • Proper test setup using beforeEach
  • Reusable helper functions
  • Comprehensive edge case coverage
  • Consistent assertion patterns

angular/angularJs

test/e2e/tests/base-tag.spec.js

            
'use strict';

describe('SCE URL policy when base tags are present', function() {
  beforeEach(function() {
    loadFixture('base-tag');
  });


  it('allows the page URL (location.href)', function() {
    expectToBeTrusted(browser.getCurrentUrl(), true);
  });

  it('blocks off-origin URLs', function() {
    expectToBeTrusted('http://evil.com', false);
  });

  it('allows relative URLs ("/relative")', function() {
    expectToBeTrusted('/relative', true);
  });

  it('allows absolute URLs from the base origin', function() {
    expectToBeTrusted('http://www.example.com/path/to/file.html', true);
  });

  it('tracks changes to the base URL', function() {
    browser.executeScript(
        'document.getElementsByTagName("base")[0].href = "http://xxx.example.com/";');
    expectToBeTrusted('http://xxx.example.com/path/to/file.html', true);
    expectToBeTrusted('http://www.example.com/path/to/file.html', false);
  });


  // Helpers
  function expectToBeTrusted(url, isTrusted) {
    var urlIsTrusted = browser.executeScript('return isTrustedUrl(arguments[0])', url);
    expect(urlIsTrusted).toBe(isTrusted);
  }
});