I want to be able to turn on and off a $httpBackend mock in my angularJS app.
That means I want to inject the $httpBackend lazily/on demand. It would also be nice to be able to turn it on and off again.
For example to provide input data for an AngularJS app that is being previewed from a CMS.
The below code does only work if I move the ngMockE2E to an ordinary dependency, and inject $httpBackend to my factory the standard way.
The code sets upp $httpBackend on all calls from a config file, and then responds to all of them...
const registerCalls = () => {
const injectormock = angular.injector(['ngMockE2E']); //lazy load not working as expected
const $httpBackend = injectormock.get('$httpBackend'); //lazy load not working as expected.
//Pass through for resources:
$httpBackend.whenGET(/.*.html/).passThrough();
$httpBackend.whenGET(/.*.json/).passThrough();
//API calls should be mocked:
const apiCalls = {};
for (var call in apiConfig) {
if ({}.hasOwnProperty.call(apiConfig, call)) {
const callConfig = apiConfig[call];
const url = angular.isDefined(callConfig.regex) ? callConfig.regex : callConfig.url();
if (callConfig.method === 'GET') {
apiCalls[call] = $httpBackend.whenGET(url);
} else if (callConfig.method === 'POST') {
apiCalls[call] = $httpBackend.whenPOST(url);
}
}
}
return apiCalls;
}
const success = function() {
const apiCalls = registerCalls();
for (var call in apiConfig) {
let response = {};
if (angular.isDefined(apiConfig[call].response)) {
response = apiConfig[call].response();
}
apiCalls[call].respond(200, response);
}
};
How can I setup the $httpBackend so that it can be activated/deactivated while the AngularJS app is running?