HTTP Backend Mock for Protractor
httpbackend is an npm module designed to mock HTTP requests specifically within an AngularJS application being tested by Protractor. Its primary function is to intercept `XMLHttpRequest` and `$http` requests made by the AngularJS application, allowing developers to define custom responses for specific URLs and methods. This facilitates isolated and deterministic testing of frontend logic without relying on a live backend server. The package is currently at version 2.0.0, last published in June 2017. Due to its tight coupling with AngularJS and Protractor, both of which are considered legacy technologies, the package is no longer actively maintained. Its release cadence was sporadic and has ceased, making it unsuitable for modern web development workflows involving current Angular versions (2+), React, Vue, or contemporary testing frameworks like Cypress or Playwright. Its key differentiator was its direct integration with Protractor's `browser` object for injecting mock modules into AngularJS applications.
Common errors
-
TypeError: browser is not defined
cause This error occurs when `new HttpBackend(browser)` is called, but the Protractor `browser` global object is not available in the test context.fixEnsure your test is running within a Protractor environment where the `browser` object is automatically provided. If not, you might need to manually require Protractor and assign `protractor.browser`. -
Error: [$injector:modulerr] Failed to instantiate module ngMock due to: Error: [ng:btstrp] App already bootstrapped with this element
cause This usually indicates that `angular-mocks.js` was not loaded correctly or that an attempt was made to bootstrap an AngularJS application twice, often in a Protractor context when the mock module injection conflicts with an existing bootstrap.fixVerify `angular-mocks.js` is included in your application under test. Ensure your Protractor `onPrepare` function correctly configures the mock module loading without conflicting with the app's initial bootstrapping. -
Error: No fixtures matched method GET to URL /api/data. There are no fixtures configured.
cause `httpbackend` did not find a `whenGET`, `whenPOST`, etc., rule that matched the actual HTTP request made by the application under test.fixDouble-check the method (GET, POST, PUT, etc.) and URL pattern provided to `backend.whenGET(/regex/)` or `backend.whenGET('/exact/path')` against the actual request made by your AngularJS application. Use regular expressions for more flexible matching.
Warnings
- breaking The `httpbackend` package is designed exclusively for AngularJS applications tested with Protractor. Both technologies are now considered legacy and are largely unmaintained. It is not compatible with modern Angular (2+), React, Vue, or contemporary testing frameworks like Cypress or Playwright.
- gotcha This package is CommonJS-only and does not support ES Modules (`import`/`export` syntax). Attempting to use ESM imports will lead to runtime errors.
- gotcha The `angular-mocks` library, a peer dependency for `httpbackend`'s functionality, must be explicitly included and loaded in your AngularJS application's HTML page *before* your application code, typically via a `<script>` tag. `httpbackend` does not manage this dependency directly.
- gotcha The package has not been updated since 2017 and is effectively abandoned. It may contain unpatched security vulnerabilities, critical bugs, or be incompatible with newer Node.js versions or browser environments. Using it in production or sensitive testing environments is strongly discouraged.
Install
-
npm install httpbackend -
yarn add httpbackend -
pnpm add httpbackend
Imports
- HttpBackend
import { HttpBackend } from 'httpbackend';const HttpBackend = require('httpbackend');
Quickstart
const HttpBackend = require('httpbackend');
const protractor = require('protractor');
const browser = protractor.browser;
const element = protractor.element;
const by = protractor.by;
describe('HTTP Backend Mock Example', function() {
let backend = null;
beforeAll(function() {
// Assuming 'browser' is globally available in Protractor tests or injected.
backend = new HttpBackend(browser);
});
afterEach(function() {
// Clears all defined fixtures after each test to prevent side effects.
backend.clear();
});
it('should mock a GET request with a string response', function() {
// Define a mock response for any GET request to '/api/data'
backend.whenGET('/api/data').respond('Mocked Data');
// Navigate to an application URL that triggers a GET request to '/api/data'
// Ensure your Angular app on 127.0.0.1:8080 makes this request and displays the result.
browser.get('http://127.0.0.1:8080/some-page-that-fetches-data');
// Example: Assert on an element that displays the fetched data
// (Assuming an element with binding 'dataResult' displays the response)
const resultElement = element(by.binding('dataResult'));
expect(resultElement.getText()).toEqual('Mocked Data');
});
it('should mock a POST request with a function response mirroring input', function() {
// Define a mock response for POST requests, returning the request data back.
backend.whenPOST('/api/submit').respond(function(method, url, data) {
return [200, { receivedData: JSON.parse(data) }];
});
browser.get('http://127.0.0.1:8080/form-page');
// Simulate user interaction that triggers a POST request
element(by.model('formData.name')).sendKeys('Test User');
element(by.css('#submitButton')).click();
// Assert that the application processed the mocked response correctly
const responseDisplay = element(by.binding('postResponse.receivedData.name'));
expect(responseDisplay.getText()).toEqual('Test User');
});
});