Protractor - how to call the WebDriver methods? - angularjs

I'm trying to use the deleteAllCookies() function from WebDriver from a Protractor test spec.
I've tried:
browser.driver.deleteAllCookies(); // undefined error
browser.driver.options.deleteAllCookies(); // undefined error
browser.manage().deleteAllCookies(); // doesn't seem to be deleting cookies
How do I call/use this function correctly?

This works for me with protractor 1.5.0, selenium-webdriver: "2.44.0"
browser.driver.manage().deleteAllCookies();

In protractor the way to delete all your cookies is:
ptor.manage().deleteAllCookies();

Related

CORS error - Error: Cross origin http://localhost forbidden - in ReactJS/Jest test only

I'm running into a problem where the request I am making to an outside API is working fine in execution, but when runing a Jest/Enzyme test it gives me a CORS error. The function in question is using a JsonRpc implementation from an API, and using fetch from node-fetch. Not sure if there are settings for CORS I can apply somewhere?
I tried many variations of async waits in Jest/Enzyme testing framework but am still running into issues.
test("it should do something", done => {
const component = shallow(<CustomComponent />)
component.instance().customAsyncFunction( result => {
expect(result.length).toEqual(5)
done()
})
// return component.instance().customAsyncFunction().then(data => {
// expect(data.length).toEqual(5)
// })
})
I tried the above and a few other methods (like setTimeout and awaiting it) and get the CORS error.
The results I'm getting are:
console.error
node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Cross origin http://localhost forbidden
at dispatchError (...\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:65:19)
at Request.client.on.res (...\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:679:38)
at Request.emit (events.js:198:13)
at Request.onRequestResponse (...\node_modules\request\request.js:1066:10)
at ClientRequest.emit (events.js:203:15)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:556:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
at TLSSocket.socketOnData (_http_client.js:442:20) undefined
Any ideas?
Jest allows you to set a setup script file. This file will be required before everything else and gives you a chance to modify the environment in which the tests will run. This way you can unset XMLHttpRequest before axios is loaded and the adapter type evaluated since imports are hoisted.
Link:https://facebook.github.io/jest/docs/configuration.html#setuptestframeworkscriptfile-string
In package.json
{
...,
"jest": {
...,
"setupTestFrameworkScriptFile": "./__tests__/setup.js",
...
},
...
}
__tests__/setup.js
global.XMLHttpRequest = undefined;
The error happens because the external API you call during the tests has a CORS restriction different than Jest's default jsdom one has (http://localhost).
To fix this for Jest v24 - v27 you have to set the appropriate testURL (see the docs) in your Jest config (e.g. jest.config.js):
{
// Other config values here ...
"testURL": "http://localhost:8080"
}
In testURL you have to put the actual URL allowed by CORS at your remote API side.
NB: since v28 the option is organized differentlty that requires different update in Jest config.
Assuming you actually want to call the real API during your tests rather than just mock it, you'll need to make sure the server sends an appropriate "access-control-allow-origin" header (obviously the exact mechanism for doing this depends on your server platform)
1) what you're probably looking for is to instead mock the promise or whatever function is being ran using jest.mock(), then assert that that mock was called (with the correct params)
Jest tests are unit tests that shouldn't really talk to your API
2) most likely something with your env vars while in test mode, process.env.NODE_ENV is set to "test" during jest which might be changing something or maybe one of your own custom config env vars
By settting a testURL option which is a valid URL you want in jest config will resovle this problem.
https://jestjs.io/docs/configuration#testurl-string

How to fix the below test case when i am migrating from angularjs 1.6.9 to 1.7.8

i am trying to migrate my angularjs application from v1.6.9 to v1.7.8. my test case are failing with
angular-mock.js($rootScope)
ERROR: No response Defined! in angularjs/angular-mocks.js(1607)
ERROR:$rootScope:INPROG
since i am new to jasmine karma testing i have tried with $rootscope.flush(). but i am not able to resolve it .
this is my first unit testing with Angularjs and jasmine karma, not able to find the exact reason and i have gone through the release notes of the other releases as well.
with $rootScope i found that they have modified its scope to the function not generic.
Below is my spec.js:
I am getting error with $rootscope,flush(). could some please help me out to resolve this issue as it is required.
$httpBackend.when('GET','/application/api/prefernce-definition')
.respond(successResponsePrefernces);
$httpBackend.when('POST','/application/api/setprefernce-definition')
.respond(201);
$httpBackend.when('POST','/application/api/v1/set-prefernces');
$httpBackend.when('POST','/application/api/v2/balances')
.respond(accountApiResponse);
//assertion for expecting proper get request for preferences-definition
$httpBackend.expectGET(,'/application/api/v1/prefernce-prefernces');
//fetch and set prefernces
$scope.onclickSetting();
$rootScope.flush();
$timeout.flush();
//now save the settings
$scope.saveViewSettings();
// getting error in this line after the flush
$rootScope.flush();
$timeout.flush();
var viewMode = $scope.model.viewSettings.viewMode,
viewModeExpected = successResponsePreferences.preferenceDefinitionList[0];
expect(viewMode.default).toBe(viewModeExpected.defaultPreferenceValue);
expect(viewMode.selected).toBe(viewModeExpected.currentUserPreferenceValue);
expect($scope.$broadcast).toHaveBeenCalledWith("ShowFilter");
//should update the prefernces in cache
expect(viewMode.selected).toBe(cacheService.getPreferences().viewMode);
expect(analyticsService.sendAction).toHaveBeenCalledwith(
Constant.ACCOUNT_BALANCES.MODULE_NAME,
Constant.ACCOUNT_BALANCES,VIEW_SETTINGS,
[]
);
expect(analyticsService.sendAction).toHaveBeenCalledwith(
Constant.ACCOUNT_BALANCES.MODULE_NAME,
Constant.ACCOUNT_BALANCES,VIEW_SETTINGS,
[Constant.EXTD_MODE, Constant.NO_GROUPING]
);
});
Below are the errors:
Error: No response defined! In
../bower_components/angular-mocks/angular-mocks.js(line 1607) $httpBackend#/../bower_components/angular-mocks/angular-mocks.js:1607:63.

Closing a window.confirm in protractor with phantomJs

I'm writing E2E tests with Protractor for my AngularJS app.
At some point the browser will encounter a window.confirm.
When using Chrome as the test browser, the following code works fine :
var ptor = protractor.getInstance();
ptor.switchTo().alert().accept();
But on PhantomJS it raises the following error :
UnknownError: Invalid Command Method
==== async task ====
WebDriver.switchTo().alert()
at tests/E2E/spec/search.spec.js:73:33
==== async task ====
Asynchronous test function: it()
Error
at null.<anonymous> (tests/E2E/spec/search.spec.js:63:5)
at Object.<anonymous> (tests/E2E/spec/search.spec.js:6:1)
Any clue on how to handle it with PhantomJS ?
Since there is no support yet for switchTo().alert() for PhantomJS/GhostDriver
I went for the following solution : mocking window.confirm as following :
beforeEach(function() {
// bypassing PhantomJS 1.9.7/GhostDriver window.confirm (or alert) bug.
// as WebDriver's switchTo().alert() is not implemented yet.
browser.executeScript('window.confirm = function() {return true;}')
});
NB: I used jasmine for my Protractor tests, therefore I needed to put it in the beforeEach, else it would have no effect.

Protractor: Invalid locator error with isElementPresent

I have the following simple line of code in my e2e test...
var promise = ptor.isElementPresent(element(by.binding('firstName')));
I get an error that says TypeError: Invalid locator. I don't see many other people getting this error after googling it. Where did I make an error?
I believe the syntax is(remove element(...)...
var promise = ptor.isElementPresent(by.binding('firstName'));

Karma Jasmine PhantomeJS test failing ramdomly

I have a really strange behavior in my test for a simple angularJS app
Setup:
Karma v0.10.9
PhantomJS 1.9.7
All test passing the first time ( sometimes the second or third too :-) ) But after a while test failing randomly
There are two kinds of errors
TypeError: 'null' is not an object (evaluating 'errorForStack.stack')
at workFn (<my_path>/angular-mocks.js:1811)
and
Error: SECURITY_ERR: DOM Exception 18
//Line $window.openDatabase('myDB', "", 'Offline DB', 5 * 1024 * 1024);
Problem occurs on Windows and Linux
Current fix -> restart Karma --> But i hate this solution since continuous testing is just great
Any suggestions ?
Fixed the first problem ( Bug in angular-mocks.js ).
Second problem fixed by mocking openDatabase.
Thx for the help

Resources