AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
SKILL verified MIT Self-run

Angularjs Unit Testing

skill-greedychipmunk-agent-skills-angularjs-unit-test · by greedychipmunk

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

No reviews yet
0 installs
11 views
0.0% view→install

Install

$ agentstack add skill-greedychipmunk-agent-skills-angularjs-unit-test

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution Used

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/skill-greedychipmunk-agent-skills-angularjs-unit-test)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
1mo ago

Declared compatibility

Claude CodeClaude Desktop

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Angularjs Unit Testing? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

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](#migration-path-angularjs--angular) 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
  1. Mocking & Spying
  • Use Jasmine spies or Jest mocks to mock functions and verify calls
  • Mock HTTP responses and service dependencies
  • Simulate user interactions
  1. Test Fixtures
  • Create reusable test data and helper functions
  • Use beforeEach/afterEach for common setup/teardown
  • Reduce test duplication
  1. Edge Case Testing
  • Test boundary conditions, empty states, and error scenarios
  • Validate error handling and graceful degradation
  • Test asynchronous operations and race conditions
  1. Snapshot Testing (Jest)
  • Capture expected component output
  • Detect unintended changes in UI rendering
  1. 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: ['/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

``bash 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.

  1. Create a Jest setup file
  • Add setup-jest.js or setup-jest.ts
  • Load angular, angular-mocks, and any shared test polyfills there
  1. 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
  1. Load AngularJS modules in Jest

``javascript beforeEach(() => { require('angular'); require('angular-mocks'); angular.mock.module('myApp'); }); ``

  1. Migrate spies and stubs
  • spyOn(obj, 'method')jest.spyOn(obj, 'method')
  • jasmine.createSpy()jest.fn()
  • jasmine.createSpyObj()jest.fn() or explicit mock objects
  1. 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
  1. 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('')(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('')(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') {

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [greedychipmunk](https://github.com/greedychipmunk)
- **Source:** [greedychipmunk/agent-skills](https://github.com/greedychipmunk/agent-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.