agentleFS
greedychipmunkgreedychipmunk/agent-skills/angularjs-unit-test/skill.md

angularjs-unit-testing

Skill19 starsChanged 6 months agoMITView on GitHub

Use this skill for AngularJS unit testing, maintenance, and migration tasks

  • Installs packages

The file

Show its rules and text

We split this skill into the rules it gives an agent

53 rules. About 0 are common, 41 are distinctive, and 12 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈41

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 12

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Controllers: Write tests for controller logic, state management, and event handling

    line 18
  2. Distinctive:

    Services: Test factory/service dependencies, HTTP calls, and business logic

    line 19
  3. Distinctive:

    Directives: Test directive compilation, linking, and DOM manipulation

    line 21
  4. Distinctive:

    Dependency Injection: Test with mocked and real dependencies

    line 24
  5. Distinctive:

    Scope Management: Test scope lifecycle, watchers, and event broadcasting

    line 25
  6. Distinctive:

    Use Jasmine spies or Jest mocks to mock functions and verify calls

    line 39
  7. Distinctive:

    Create reusable test data and helper functions

    line 44
  8. Distinctive:

    Use beforeEach/afterEach for common setup/teardown

    line 45
  9. Distinctive:

    Test boundary conditions, empty states, and error scenarios

    line 49
  10. Distinctive:

    Test asynchronous operations and race conditions

    line 51
  11. Distinctive:

    Prefer fake timers, controlled promises, and isolated state over timing-sensitive assertions

    line 58
  12. Distinctive:

    Use these steps when moving an AngularJS test suite from Jasmine/Karma to Jest:

    line 131
  13. Very specific:

    Add @angular/core when the repo is hybrid or actively migrating toward Angular.

    line 138
  14. Very specific:

    Add setup-jest.js or setup-jest.ts

    line 141
  15. Very specific:

    Use jest.config.js with testEnvironment: 'jsdom'

    line 145
  16. Distinctive:

    Add a transform for legacy JavaScript sources

    line 146
  17. Distinctive:

    Keep template or DOM-specific setup in the Jest bootstrap file

    line 147
  18. Very specific:

    Prefer fetch mocks or MSW for new Jest tests

    line 164
  19. Very specific:

    Keep $httpBackend only for legacy tests that are expensive to rewrite immediately

    line 165
  20. Distinctive:

    Use fake timers for scheduled work and debounce/throttle logic

    line 183
  21. Distinctive:

    Keep async work controlled with explicit promise resolution and digest flushing

    line 184
  22. Distinctive:

    Avoid real browser/network dependencies in unit tests

    line 186
  23. Distinctive:

    Prefer fixed test data over generated or time-based values

    line 187
  24. Distinctive:

    Keep integration tests as the middle layer, not the base

    line 205
  25. Distinctive:

    Use e2e tests sparingly because they are slower and more environment-sensitive

    line 206
  26. Distinctive:

    All Jasmine tests follow this standard structure:

    line 212
  27. Distinctive:

    Use meaningful test names that describe expected behavior

    line 290
  28. Distinctive:

    Create reusable test data fixtures

    line 294
  29. Distinctive:

    Use helper functions to reduce duplication

    line 295
  30. Distinctive:

    Avoid shared state between tests

    line 300
  31. Distinctive:

    Use actual data structures when possible

    line 304
  32. Distinctive:

    Avoid overly simplified or unrealistic mocks

    line 305
  33. Distinctive:

    Test happy paths, edge cases, and error scenarios

    line 309
  34. Distinctive:

    Test async operations and race conditions

    line 310
  35. Distinctive:

    Use in-memory mocks instead of real HTTP requests

    line 314
  36. Distinctive:

    Avoid unnecessary database operations

    line 315
  37. Distinctive:

    Write tests that are easy to understand

    line 318
  38. Distinctive:

    Use the AAA pattern for clarity

    line 319
  39. Distinctive:

    Document complex test logic with comments

    line 320
  40. Very specific:

    Check that module is loaded: beforeEach(module('myApp'))

    line 565
  41. Very specific:

    Verify dependencies are injected: beforeEach(inject(...))

    line 566
  42. Distinctive:

    Check for syntax errors

    line 567
  43. Very specific:

    Ensure promises are resolved: $rootScope.$apply() or $httpBackend.flush()

    line 570
  44. Very specific:

    Use done() callback: it('...', function(done) { ...

    line 571
  45. Distinctive:

    Verify mock is set up before service call

    line 575
  46. Distinctive:

    Check exact URL match in expectations

    line 576
  47. Very specific:

    Use passThrough() for unmocked requests

    line 577
  48. Distinctive:

    Test error conditions and edge cases

    line 581
  49. Very specific:

    If your tests use Karma with a real browser, use karma-chrome-launcher with headless Chrome

    line 590
  50. Distinctive:

    When the time comes to move off AngularJS, here is the conceptual mapping:

    line 620
  51. Distinctive:

    Start Small: Write tests for a single component

    line 637
  52. Distinctive:

    Choose the Right Runner: Keep Jasmine/Karma only for existing suites.

    line 638
  53. Very specific:

    Plan the Migration: When ready, use @angular/upgrade for incremental migration — your test suite migrates with you

    line 643

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
skill.md

AngularJS Unit Testing Skill

Overview

This skill specializes in writing, refactoring, and maintaining high-quality unit tests for AngularJS (1.x) applications. It covers controllers, services, filters, directives, HTTP mocking, promises, and dependency injection — everything you need to keep an AngularJS codebase well-tested and reliable.

Note: AngularJS reached end-of-life in December 2021. It receives only critical security fixes. New projects should use Angular 19+. For teams maintaining AngularJS codebases, this skill provides the latest testing patterns, tooling, and migration guidance. See Migration Path at the bottom of this document.

Skill Capabilities

Core Testing Competencies

  • Controllers: Write tests for controller logic, state management, and event handling
  • Services: Test factory/service dependencies, HTTP calls, and business logic
  • Filters: Validate filter transformations and edge cases
  • Directives: Test directive compilation, linking, and DOM manipulation
  • HTTP Mocking: Mock HTTP calls using $httpBackend (Jasmine/Karma) or MSW/fetch mocks (Jest)
  • Promises & Async: Handle $q, deferred objects, and $timeout
  • Dependency Injection: Test with mocked and real dependencies
  • Scope Management: Test scope lifecycle, watchers, and event broadcasting
  • Coverage Analysis: Generate and interpret code coverage reports
  • Test Organization: Structure tests following best practices and maintainability principles
  • Framework Choice: Jest for new work and hybrid repos; Jasmine/Karma for existing suites

Testing Patterns

This skill implements the following testing patterns:

  1. AAA Pattern (Arrange-Act-Assert)
    • Organize tests with clear setup, execution, and verification phases
    • Improves readability and maintainability
  2. Mocking & Spying
    • Use Jasmine spies or Jest mocks to mock functions and verify calls
    • Mock HTTP responses and service dependencies
    • Simulate user interactions
  3. Test Fixtures
    • Create reusable test data and helper functions
    • Use beforeEach/afterEach for common setup/teardown
    • Reduce test duplication
  4. Edge Case Testing
    • Test boundary conditions, empty states, and error scenarios
    • Validate error handling and graceful degradation
    • Test asynchronous operations and race conditions
  5. Snapshot Testing (Jest)
    • Capture expected component output
    • Detect unintended changes in UI rendering
  6. Deterministic Async
    • Prefer fake timers, controlled promises, and isolated state over timing-sensitive assertions

Testing Frameworks & Test Runners

Jasmine (Legacy Default)

Jasmine remains the safest choice when you are preserving an existing AngularJS + Karma suite.

Key Concepts:

  • describe(): Group related tests into a test suite
  • it(): Define individual test cases
  • expect(): Create assertions
  • beforeEach() / afterEach(): Setup and teardown hooks
  • spyOn() / jasmine.createSpy(): Mock functions and track calls

Setup:

npm install --save-dev jasmine karma karma-jasmine karma-chrome-launcher

Use when:

  • You are maintaining an existing Jasmine/Karma suite
  • You want the smallest possible change set for legacy AngularJS code

Jest (Recommended)

Jest is the modern default for AngularJS test maintenance and migration work. It runs tests in parallel, has stronger mocking APIs, supports snapshots, and includes built-in coverage reporting.

Key Concepts:

  • describe(): Group related tests
  • test() or it(): Define individual test cases
  • expect(): Create assertions
  • beforeEach() / afterEach(): Setup and teardown hooks
  • jest.fn(): Create mock functions
  • jest.spyOn(): Spy on existing methods
  • jest.mock(): Mock modules

Setup:

npm install --save-dev jest jest-preset-angular angular-mocks
npm install @angular/core

Jest Configuration (jest.config.js):

module.exports = {
  preset: 'jest-preset-angular',
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
  transform: {
    '^.+\.js$': 'babel-jest'
  },
  collectCoverage: true,
  collectCoverageFrom: ['src/**/*.js', '!src/**/*.spec.js']
};

Use when:

  • You want faster feedback from parallel execution
  • You need better mocking, snapshots, and coverage out of the box
  • You are preparing an AngularJS codebase for an Angular migration

Karma (Legacy Runner)

Karma is the legacy browser test runner traditionally paired with Jasmine. It is still usable for existing suites, but it has seen no major releases since 2021 and should not be the basis for new investment.

Configuration:

  • karma.conf.js: Main configuration file
  • Specifies browser environment, files to load, and plugins
  • Supports code coverage reporting and CI integration

Jest Migration Guide

Use these steps when moving an AngularJS test suite from Jasmine/Karma to Jest:

  1. Install the core tooling
    npm install --save-dev jest jest-preset-angular angular-mocks
    npm install @angular/core
    Add @angular/core when the repo is hybrid or actively migrating toward Angular.
  2. Create a Jest setup file
    • Add setup-jest.js or setup-jest.ts
    • Load angular, angular-mocks, and any shared test polyfills there
  3. Configure Jest for AngularJS files
    • Use jest.config.js with testEnvironment: 'jsdom'
    • Add a transform for legacy JavaScript sources
    • Keep template or DOM-specific setup in the Jest bootstrap file
  4. Load AngularJS modules in Jest
    beforeEach(() => {
      require('angular');
      require('angular-mocks');
      angular.mock.module('myApp');
    });
  5. Migrate spies and stubs
    • spyOn(obj, 'method') → jest.spyOn(obj, 'method')
    • jasmine.createSpy() → jest.fn()
    • jasmine.createSpyObj() → jest.fn() or explicit mock objects
  6. Replace $httpBackend where practical
    • Prefer fetch mocks or MSW for new Jest tests
    • Keep $httpBackend only for legacy tests that are expensive to rewrite immediately
  7. Reset state between tests
    • Use jest.clearAllMocks() / jest.resetAllMocks()
    • Recreate AngularJS modules and services in beforeEach()

Handling Environmental Flakiness

Legacy AngularJS suites often fail because the environment is unstable, not because the code is broken.

Common sources of flakiness:

  • Timing issues and race conditions
  • Shared state between tests
  • Browser environment differences
  • Network-dependent tests and real external services
  • Time zone, locale, and date-sensitive logic

Deterministic test patterns:

  • Use fake timers for scheduled work and debounce/throttle logic
  • Keep async work controlled with explicit promise resolution and digest flushing
  • Reset shared state, mocks, and module caches in afterEach()
  • Avoid real browser/network dependencies in unit tests
  • Prefer fixed test data over generated or time-based values

js-env-sanitizer pattern:

  • Snapshot and restore environment-dependent globals around each test
  • Isolate window, document, localStorage, Date, Math.random, feature flags, and DOM mutations
  • This is especially useful in long-lived AngularJS suites where hidden environment coupling causes intermittent failures

Test Pyramid Guidance for Legacy Codebases

Legacy AngularJS codebases often have an inverted test pyramid: too many end-to-end tests and too few unit tests.

Recommended shape:

  • Base: many fast unit tests for controllers, services, filters, and directives
  • Middle: fewer integration tests for module wiring, routing, and API boundaries
  • Top: a small number of end-to-end tests for critical user journeys only

Guidance:

  • Shift coverage toward unit tests first
  • Keep integration tests as the middle layer, not the base
  • Use e2e tests sparingly because they are slower and more environment-sensitive

Test Structure

Jasmine Test Structure (Legacy Default)

All Jasmine tests follow this standard structure:

describe('Component Name', function() {
  var componentUnderTest, dependencies;

  beforeEach(module('myApp'));

  beforeEach(inject(function($injector) {
    componentUnderTest = $injector.get('ComponentName');
    dependencies = $injector.get('DependencyName');
  }));

  afterEach(function() {
    // Cleanup code
  });

  describe('Functionality Group', function() {
    it('should do something specific', function() {
      // Arrange
      var input = 'test';

      // Act
      var result = componentUnderTest.method(input);

      // Assert
      expect(result).toBe('expected');
    });
  });
});

Jest Test Structure (Recommended)

Jest tests follow a similar structure with modern mocking and cleaner teardown:

describe('Component Name', () => {
  let componentUnderTest;
  let dependency;

  beforeEach(() => {
    jest.clearAllMocks();
    // Setup code or mock initialization
    dependency = { method: jest.fn() };
    componentUnderTest = require('./component');
  });

  afterEach(() => {
    // Cleanup code
  });

  describe('Functionality Group', () => {
    test('should do something specific', () => {
      // Arrange
      const input = 'test';

      // Act
      const result = componentUnderTest.method(input, dependency);

      // Assert
      expect(result).toBe('expected');
    });
  });
});

Key Differences:

  • Jest uses jest.fn() / jest.spyOn() instead of Jasmine spies for modern test code
  • Jest uses test() or it() (both work)
  • Jest auto-discovers .spec.js and .test.js files
  • Jest provides built-in snapshot testing and code coverage

Best Practices

1. Test Organization

  • One test file per component (e.g., controller.spec.js for controller.js)
  • Organize tests into logical groups using describe()
  • Use meaningful test names that describe expected behavior

2. DRY Principle (Don't Repeat Yourself)

  • Extract common setup into beforeEach() blocks
  • Create reusable test data fixtures
  • Use helper functions to reduce duplication

3. Test Independence

  • Each test should be independent and runnable in any order
  • Clean up resources in afterEach()
  • Avoid shared state between tests

4. Realistic Mocks

  • Mock external dependencies realistically
  • Use actual data structures when possible
  • Avoid overly simplified or unrealistic mocks

5. Comprehensive Coverage

  • Aim for 80%+ code coverage
  • Test happy paths, edge cases, and error scenarios
  • Test async operations and race conditions

6. Performance

  • Keep tests fast
  • Use in-memory mocks instead of real HTTP requests
  • Avoid unnecessary database operations

7. Maintainability

  • Write tests that are easy to understand
  • Use the AAA pattern for clarity
  • Document complex test logic with comments
  • Refactor tests when the component changes

Common Testing Scenarios

Testing Controllers

describe('UserController', function() {
  var $scope, controller;

  beforeEach(module('myApp'));
  beforeEach(inject(function($controller, $rootScope) {
    $scope = $rootScope.$new();
    controller = $controller('UserController', {
      $scope: $scope
    });
  }));

  it('should initialize with default values', function() {
    expect($scope.users).toBeDefined();
  });

  it('should load users on init', function() {
    expect($scope.users.length).toBeGreaterThan(0);
  });
});

Testing Services

describe('UserService', function() {
  var userService, $httpBackend;

  beforeEach(module('myApp'));
  beforeEach(inject(function(_UserService_, _$httpBackend_) {
    userService = _UserService_;
    $httpBackend = _$httpBackend_;
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
  });

  it('should fetch users from API', function() {
    var expectedUsers = [{ id: 1, name: 'John' }];
    $httpBackend.expectGET('/api/users').respond(expectedUsers);

    userService.getUsers().then(function(users) {
      expect(users).toEqual(expectedUsers);
    });

    $httpBackend.flush();
  });
});

Testing with Promises

describe('PromiseService', function() {
  var service, $q, $rootScope;

  beforeEach(inject(function(_Service_, _$q_, _$rootScope_) {
    service = _Service_;
    $q = _$q_;
    $rootScope = _$rootScope_;
  }));

  it('should handle promise resolution', function() {
    var deferred = $q.defer();
    var result;

    service.asyncOperation().then(function(data) {
      result = data;
    });

    deferred.resolve('success');
    $rootScope.$apply();

    expect(result).toBe('success');
  });
});

Testing Component Directives

AngularJS 1.5+ component directives (bindings, controllerAs) are the recommended pattern for new code and the easiest to migrate to Angular later.

describe('userCard component', function() {
  var $compile, $rootScope, element, scope;

  beforeEach(module('myApp'));
  beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    scope.user = { name: 'Alice', role: 'admin' };
  }));

  it('should render user name and role', function() {
    element = $compile('<user-card user="user"></user-card>')(scope);
    scope.$digest();

    var isolated = element.isolateScope().$ctrl;
    expect(isolated.user.name).toBe('Alice');
    expect(element.text()).toContain('admin');
  });

  it('should call onSelect when clicked', function() {
    scope.onSelect = jasmine.createSpy('onSelect');
    element = $compile('<user-card user="user" on-select="onSelect(user)"></user-card>')(scope);
    scope.$digest();

    element.isolateScope().$ctrl.onSelect({ user: scope.user });
    expect(scope.onSelect).toHaveBeenCalledWith(scope.user);
  });
});

Testing $httpBackend with Request Matchers

For APIs with dynamic segments or query parameters, use regex or function matchers instead of exact URL strings:

// Match any GET to /api/users with query params
$httpBackend.expectGET(/\/api\/users\?.*page=/).respond(200, mockResponse);

// Match by function
$httpBackend.expectGET(function(url) {
  return url.indexOf('/api/users') === 0 && url.indexOf('page=') > -1;
}).respond(200, mockResponse);

Testing $on / $broadcast Events

describe('event-driven service', function() {
  var $rootScope, service;

  beforeEach(inject(function(_$rootScope_, _EventService_) {
    $rootScope = _$rootScope_;
    service = _EventService_;
  }));

  it('should react to user:updated event', function() {
    var handler = jasmine.createSpy('handler');
    $rootScope.$on('user:updated', handler);

    $rootScope.$broadcast('user:updated', { id: 42 });
    expect(handler).toHaveBeenCalled();
    expect(handler.calls.argsFor(0)[1]).toEqual({ id: 42 });
  });
});

Debugging Tests

Jasmine Debugging

// Skip a test
xit('should do something', function() { ... });

// Run only this test
fit('should do something', function() { ... });

// Console logging in tests
it('should debug', function() {
  console.log('Current state:', $scope);
  expect(true).toBe(true);
});

Jest Debugging

// Skip a test
test.skip('should do something', () => { ... });

// Run only this test
test.only('should do something', () => { ... });

// Debug with Node inspector
// Run: node --inspect-brk node_modules/.bin/jest --runInBand

Integration with CI/CD

GitHub Actions Example

name: Test
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: npm
      - run: npm ci
      - run: npm test -- --coverage
      - uses: codecov/codecov-action@v4
        with:
          files: ./coverage/lcov.info

Jenkins Example

pipeline {
  stages {
    stage('Test') {
      steps {
        sh 'npm ci'
        sh 'npm test'
        publishHTML([
          reportDir: 'coverage',
          reportFiles: 'index.html',
          reportName: 'Coverage Report'
        ])
      }
    }
  }
}

Resources

Troubleshooting

Tests not running

  • Check that module is loaded: beforeEach(module('myApp'))
  • Verify dependencies are injected: beforeEach(inject(...))
  • Check for syntax errors

Async tests timing out

  • Ensure promises are resolved: $rootScope.$apply() or $httpBackend.flush()
  • Use done() callback: it('...', function(done) { ... done(); })
  • For Jest: use async/await or return a promise

HTTP mocks not working

  • Verify mock is set up before service call
  • Check exact URL match in expectations
  • Use passThrough() for unmocked requests

Coverage gaps

  • Review untested branches in coverage reports
  • Test error conditions and edge cases
  • Mock external dependencies properly

Modern Runtime Compatibility

AngularJS was built for an older Node.js and browser ecosystem, but it still runs on modern runtimes with the right configuration.

Node.js 22 LTS

  • AngularJS 1.8.x runs on Node 22 LTS without modification
  • If your tests use Karma with a real browser, use karma-chrome-launcher with headless Chrome
  • For Jest: testEnvironment: 'jsdom' handles the browser globals — no real browser needed

Headless Chrome in CI

# GitHub Actions — headless Chrome with Karma
- uses: actions/setup-chrome@v1
  with:
    chrome-version: stable
- run: npm test
// karma.conf.js — headless Chrome for CI
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
  ChromeHeadlessNoSandbox: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox']
  }
}

Common Pitfalls on Modern Runtimes

  • V8 strict mode: AngularJS code relying on implicit globals or arguments.callee will fail in strict mode. Use 'use strict' in test files to catch these early.
  • jsdom vs. real browser: Some directive tests that depend on real layout or CSS computation may not work in jsdom. Run those with Karma + headless Chrome instead.
  • npm audit failures: AngularJS dependencies may have known vulnerabilities. Use npm audit --production to separate real risks from dev-only warnings, and consider overrides in package.json to pin patched transitive dependencies.

Migration Path: AngularJS → Angular

When the time comes to move off AngularJS, here is the conceptual mapping:

AngularJSAngular 19+
Modules / controllersStandalone components or NgModules, injectable services
$scope / $rootScopeComponent state, @Input() / @Output(), signals
$http / $resourceHttpClient
DirectivesComponents and directives with modern APIs
$q / digest cycleRxJS, promises/async-await, signals
$routeProviderAngular Router
angular.module() DITree-shakable providers, inject()
Globals and ad-hoc DOMDependency injection and testable abstractions

Hybrid migration: Use @angular/upgrade to run AngularJS and Angular side by side. Migrate component-by-component rather than rewriting the whole app at once. The AngularJS test suite stays active throughout — Jest is the best runner for hybrid repos because it handles both AngularJS and Angular test files.

Next Steps

  1. Start Small: Write tests for a single component
  2. Choose the Right Runner: Keep Jasmine/Karma only for existing suites; prefer Jest for new work and hybrid repos
  3. Understand Patterns: Study the testing patterns guide
  4. Use Templates: Reference template files for your component type
  5. Refine: Improve tests based on coverage and feedback
  6. Automate: Integrate tests into your CI/CD pipeline
  7. Plan the Migration: When ready, use @angular/upgrade for incremental migration — your test suite migrates with you

Specialization: AngularJS Unit Testing with Jasmine and Jest
Version: 2.0
Last Updated: May 2026

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.