angularjs-unit-testing
Skill19 starsChanged 6 months agoMITView on GitHub
Use this skill for AngularJS unit testing, maintenance, and migration tasks
- Installs packages
In this repository21 other files it gives its agents.
- agent-developmentSkill
- ansibleSkill
- argocdSkill
- astryxSkill
- blog-managerSkill
- datadogSkill
- dockerSkill
- github-ciSkill
- githubSkill
- helmSkill
- kubectlSkill
- mcp-builderSkill
- medusajs-developerSkill
- mermaidSkill
- nextjs-developerSkill
- pulumiSkill
- roblox-game-developmentSkill
- sentrySkill
- standard-siteSkill
- supabase-developerSkill
- terraformSkill
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
- Distinctive: line 18
Controllers: Write tests for controller logic, state management, and event handling
- Distinctive: line 19
Services: Test factory/service dependencies, HTTP calls, and business logic
- Distinctive: line 21
Directives: Test directive compilation, linking, and DOM manipulation
- Distinctive: line 24
Dependency Injection: Test with mocked and real dependencies
- Distinctive: line 25
Scope Management: Test scope lifecycle, watchers, and event broadcasting
- Distinctive: line 39
Use Jasmine spies or Jest mocks to mock functions and verify calls
- Distinctive: line 44
Create reusable test data and helper functions
- Distinctive: line 45
Use beforeEach/afterEach for common setup/teardown
- Distinctive: line 49
Test boundary conditions, empty states, and error scenarios
- Distinctive: line 51
Test asynchronous operations and race conditions
- Distinctive: line 58
Prefer fake timers, controlled promises, and isolated state over timing-sensitive assertions
- Distinctive: line 131
Use these steps when moving an AngularJS test suite from Jasmine/Karma to Jest:
- Very specific: line 138
Add @angular/core when the repo is hybrid or actively migrating toward Angular.
- Very specific: line 141
Add setup-jest.js or setup-jest.ts
- Very specific: line 145
Use jest.config.js with testEnvironment: 'jsdom'
- Distinctive: line 146
Add a transform for legacy JavaScript sources
- Distinctive: line 147
Keep template or DOM-specific setup in the Jest bootstrap file
- Very specific: line 164
Prefer fetch mocks or MSW for new Jest tests
- Very specific: line 165
Keep $httpBackend only for legacy tests that are expensive to rewrite immediately
- Distinctive: line 183
Use fake timers for scheduled work and debounce/throttle logic
- Distinctive: line 184
Keep async work controlled with explicit promise resolution and digest flushing
- Distinctive: line 186
Avoid real browser/network dependencies in unit tests
- Distinctive: line 187
Prefer fixed test data over generated or time-based values
- Distinctive: line 205
Keep integration tests as the middle layer, not the base
- Distinctive: line 206
Use e2e tests sparingly because they are slower and more environment-sensitive
- Distinctive: line 212
All Jasmine tests follow this standard structure:
- Distinctive: line 290
Use meaningful test names that describe expected behavior
- Distinctive: line 294
Create reusable test data fixtures
- Distinctive: line 295
Use helper functions to reduce duplication
- Distinctive: line 300
Avoid shared state between tests
- Distinctive: line 304
Use actual data structures when possible
- Distinctive: line 305
Avoid overly simplified or unrealistic mocks
- Distinctive: line 309
Test happy paths, edge cases, and error scenarios
- Distinctive: line 310
Test async operations and race conditions
- Distinctive: line 314
Use in-memory mocks instead of real HTTP requests
- Distinctive: line 315
Avoid unnecessary database operations
- Distinctive: line 318
Write tests that are easy to understand
- Distinctive: line 319
Use the AAA pattern for clarity
- Distinctive: line 320
Document complex test logic with comments
- Very specific: line 565
Check that module is loaded: beforeEach(module('myApp'))
- Very specific: line 566
Verify dependencies are injected: beforeEach(inject(...))
- Distinctive: line 567
Check for syntax errors
- Very specific: line 570
Ensure promises are resolved: $rootScope.$apply() or $httpBackend.flush()
- Very specific: line 571
Use done() callback: it('...', function(done) { ...
- Distinctive: line 575
Verify mock is set up before service call
- Distinctive: line 576
Check exact URL match in expectations
- Very specific: line 577
Use passThrough() for unmocked requests
- Distinctive: line 581
Test error conditions and edge cases
- Very specific: line 590
If your tests use Karma with a real browser, use karma-chrome-launcher with headless Chrome
- Distinctive: line 620
When the time comes to move off AngularJS, here is the conceptual mapping:
- Distinctive: line 637
Start Small: Write tests for a single component
- Distinctive: line 638
Choose the Right Runner: Keep Jasmine/Karma only for existing suites.
- Very specific: line 643
Plan the Migration: When ready, use @angular/upgrade for incremental migration — your test suite migrates with you
≈ “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.
Files
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:
- AAA Pattern (Arrange-Act-Assert)
- Organize tests with clear setup, execution, and verification phases
- Improves readability and maintainability
- Mocking & Spying
- Use Jasmine spies or Jest mocks to mock functions and verify calls
- Mock HTTP responses and service dependencies
- Simulate user interactions
- Test Fixtures
- Create reusable test data and helper functions
- Use beforeEach/afterEach for common setup/teardown
- Reduce test duplication
- Edge Case Testing
- Test boundary conditions, empty states, and error scenarios
- Validate error handling and graceful degradation
- Test asynchronous operations and race conditions
- Snapshot Testing (Jest)
- Capture expected component output
- Detect unintended changes in UI rendering
- 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 suiteit(): Define individual test casesexpect(): Create assertionsbeforeEach()/afterEach(): Setup and teardown hooksspyOn()/jasmine.createSpy(): Mock functions and track calls
Setup:
npm install --save-dev jasmine karma karma-jasmine karma-chrome-launcherUse 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 teststest()orit(): Define individual test casesexpect(): Create assertionsbeforeEach()/afterEach(): Setup and teardown hooksjest.fn(): Create mock functionsjest.spyOn(): Spy on existing methodsjest.mock(): Mock modules
Setup:
npm install --save-dev jest jest-preset-angular angular-mocks
npm install @angular/coreJest 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:
- Install the core tooling
Addnpm install --save-dev jest jest-preset-angular angular-mocks npm install @angular/core@angular/corewhen the repo is hybrid or actively migrating toward Angular. - Create a Jest setup file
- Add
setup-jest.jsorsetup-jest.ts - Load
angular,angular-mocks, and any shared test polyfills there
- Add
- Configure Jest for AngularJS files
- Use
jest.config.jswithtestEnvironment: 'jsdom' - Add a transform for legacy JavaScript sources
- Keep template or DOM-specific setup in the Jest bootstrap file
- Use
- Load AngularJS modules in Jest
beforeEach(() => { require('angular'); require('angular-mocks'); angular.mock.module('myApp'); }); - Migrate spies and stubs
spyOn(obj, 'method')→jest.spyOn(obj, 'method')jasmine.createSpy()→jest.fn()jasmine.createSpyObj()→jest.fn()or explicit mock objects
- Replace
$httpBackendwhere practical- Prefer
fetchmocks or MSW for new Jest tests - Keep
$httpBackendonly for legacy tests that are expensive to rewrite immediately
- Prefer
- Reset state between tests
- Use
jest.clearAllMocks()/jest.resetAllMocks() - Recreate AngularJS modules and services in
beforeEach()
- Use
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()orit()(both work) - Jest auto-discovers
.spec.jsand.test.jsfiles - Jest provides built-in snapshot testing and code coverage
Best Practices
1. Test Organization
- One test file per component (e.g.,
controller.spec.jsforcontroller.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 --runInBandIntegration 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.infoJenkins Example
pipeline {
stages {
stage('Test') {
steps {
sh 'npm ci'
sh 'npm test'
publishHTML([
reportDir: 'coverage',
reportFiles: 'index.html',
reportName: 'Coverage Report'
])
}
}
}
}Resources
- Jasmine Documentation
- Karma Test Runner
- Jest Documentation
- jest-preset-angular
- AngularJS Testing Guide
- Angular Testing Guide
- Angular Update Guide
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/awaitor 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-launcherwith 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.calleewill 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 --productionto separate real risks from dev-only warnings, and consideroverridesinpackage.jsonto pin patched transitive dependencies.
Migration Path: AngularJS → Angular
When the time comes to move off AngularJS, here is the conceptual mapping:
| AngularJS | Angular 19+ |
| Modules / controllers | Standalone components or NgModules, injectable services |
$scope / $rootScope | Component state, @Input() / @Output(), signals |
$http / $resource | HttpClient |
| Directives | Components and directives with modern APIs |
$q / digest cycle | RxJS, promises/async-await, signals |
$routeProvider | Angular Router |
angular.module() DI | Tree-shakable providers, inject() |
| Globals and ad-hoc DOM | Dependency 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
- Start Small: Write tests for a single component
- Choose the Right Runner: Keep Jasmine/Karma only for existing suites; prefer Jest for new work and hybrid repos
- Understand Patterns: Study the testing patterns guide
- Use Templates: Reference template files for your component type
- Refine: Improve tests based on coverage and feedback
- Automate: Integrate tests into your CI/CD pipeline
- Plan the Migration: When ready, use
@angular/upgradefor incremental migration — your test suite migrates with you
Specialization: AngularJS Unit Testing with Jasmine and Jest
Version: 2.0
Last Updated: May 2026
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
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.

