As I work on integrating Protractor for running tests on my Angular web application, I leverage a custom Angular service called ApiClient
for making API calls. To mock this service, I utilize browser.addMockModule
along with angular.module().factory()
. This approach allows me to effectively mock all my backend APIs. Below is a snippet of the code I use:
setup() {
// Implemented in WebDriver.
// The 'apiRequestsMap' is passed as 'map' to the anonymous function within the module.
browser.addMockModule(
'mockDataModule',
(map) =>
angular.module('mockDataModule', []).value('apiRequestsMap', map),
this.apiRequestsMap_);
const apiModuleMaker = () => {
const mockModule = angular.module('mockapiModule', ['mockDataModule']);
mockModule.factory(
'apiClient',
($q, apiRequestsMap) => ({
request: (req) => {
// Within the Browser.
// Utilizing 'apiRequestsMap' for mocking API calls.
}
}));
};
browser.addMockModule('mockapiModule', apiModuleMaker);
browser.get('www.mywebpage.com/example');
}
This method works effectively for setting up mock APIs in my Protractor tests. The key aspect is the ability to pass the this.apiRequestsMap_
variable from WebDriver to the Browser as apiRequestsMap
.
Now I am curious - can I reverse this process? How can I send a variable from the Browser back to WebDriver?
My initial attempt involved modifying the apiRequestsMap
object that was passed in. However, it seems like this was a one-way transfer. For instance, when I set apiRequestsMap.aVar = 5;
in the Browser, it does not affect this.apiRequestsMap_.aVar
.
In exploring the Protractor API, I came across browser.getRegisteredMockModules
. Unfortunately,
console.log(JSON.stringify(browser.getRegisteredMockModules()));
yielded [null, null, null, null, null]
.
I apologize for the extensive code and details provided. I am navigating through uncharted territory, so I erred on the side of caution in omitting parts of the code that might impact its functionality. Is there a better approach to directly mock API calls within WebDriver? That could serve as a viable workaround.
Alternatively, I may consider submitting a feature request/bug report to the Protractor developers.