We are new to Protractor and are going through the code to better understand its functionalists and in comparison with writing tests with selenium. As an exercise we have tried to automate the angularjs home page (http://www.angularjs.org) using page objects
Our TestSpec.js file is as follows
'use strict';
var DevelopPage = require('../test_11th/Develop_pom.js');
describe('angularjs homepage', function () {
var Devpage;
beforeEach(function () {
Devpage = new DevelopPage();
});
it('Develop page should be open', function () {
Devpage.click_develop().click();
//Devpage.Api_Reference();
//Devpage.func_link();
//Devpage.search('angular');
});
});
and the page object file Develop_pom.js is as follows
'use strict';
var DevelopPage = function () {
browser.get('http://www.angularjs.org');
};
DevelopPage.prototype = Object.create({}, {
click_develop: { function ()
{ browser.driver.findElement(By.linkText("Develop")).click(); }},
Api_Reference: { function ()
{ browser.driver.findElement(By.linkText("API Reference")).click(); }},
func_link: { function ()
{ browser.driver.findElement(By.linkText("function")).click(); }},
search: { : function (txt)
{ element(by.model('q')).click().sendKeys(txt); }}
});
while running it we are encountering the error
1) Exception loading: C:\Users\kirti.vm\AppData\Roaming\npm\node_modules\protractor\test_11th\AngularSpec.js Error
Message:
SyntaxError: Unexpected token (
Stacktrace:
SyntaxError: Unexpected token (
at require (module.js:380:17)
at Object. (C:\Users\kirti.vm\AppData\Roaming\npm\node_modules\protractor\test_11th\AngularSpec.js:4:21)
Finished in 0.012 seconds
1 test, 1 assertion, 1 failure
can you please let us know what and where we are going wrong. Can we not use page objects to implement our test and call those page objects in the spec script.
You need to export the page object at the end of the file:
module.exports = DevelopPage;
Take a look at the following example if you want to see a cleaner syntax:
https://github.com/angular/protractor/blob/master/website/test/e2e/api-page.js
Related
I upgrade sails to the #^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
var ob = await ails.helpers.testy('sayHello');
res.json({ob:ob});
helper
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: async function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
fn: async function (inputs, exits) {
^^^^^^^^
SyntaxError: Unexpected token function.......
and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed. Any chance the
source code is missing an "await"?
To assist you in hunting this down, here is a stack trace:
```
at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)
The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
sync: true, // Here is essential part
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
From the another side, you have a problem with async/await. The top most reason for this are
Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing
I am facing problem while adding third party javascript code in my payment module in magento2.
following is my code.
define(
[
'Magento_Payment/js/view/payment/cc-form',
'jquery',
'Vendorname_Modulename/js/stsdk'
'Magento_Payment/js/model/credit-card-validation/validator'
],
function (Component, $, STDirect) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendorname_Modulename/payment/module-form'
},
getCode: function() {
return 'vendor_module';
},
isActive: function() {
return true;
},
validate: function() {
STDirect.setupSDK('23842', "testnumber", 'typeofenv');
STDirect.card.createToken(number, exp_month, exp_year, ccv, function (result) {
var secretkey = '';
if(result.status==0){
secretkey = result.card.secretkey;
}
document.write(JSON.stringify(result));
alert(secretkey);
});
var $form = $('#' + this.getCode() + '-form');
return $form.validation() && $form.validation('isValid');
}
});
}
);
I have tried above code, stsdk.js is loaded in network but it gives me following error :
ReferenceError: STDirect is not defined
STDirect.setupSDK('23842', "testnumber", 'sandbox');
I have also checked by load this js file in header but same error appear.
My question is how to execute third party javascript code in define scope.
I tried with the custom javascript function after define function but it is also not callable from validate function and when I use require[] function within define function it raise error.
I appreciate any help.
I must be missing something patently obvious here, but I cannot for the life of me figure out what. I have configured Restivus like this:
Projects = new Mongo.Collection('projects');
Skills = new Mongo.Collection('skills');
Causes = new Mongo.Collection('causes');
Meteor.startup(() => {
let Api = new Restivus({
apiPath: 'api/',
auth: {
token: 'auth.apiKey',
user: function () {
return {
userId: this.request.headers['user-id'],
token: this.request.headers['login-token']
};
}
},
defaultHeaders: {
'Content-Type': 'application/json'
},
onLoggedIn: function () {
console.log(this.user.username + ' (' + this.userId + ') logged in');
},
onLoggedOut: function () {
console.log(this.user.username + ' (' + this.userId + ') logged out');
},
prettyJson: true,
useDefaultAuth: true,
version: 'v1'
});
// Add core models
Api.addCollection(Skills);
Api.addCollection(Causes);
Api.addCollection(Projects);
Api.addRoute('custom', {
get: function () {
return {
status: 'success',
data: 'get something different'
};
}
});
});
This is essentially copy-pasted from the documentation. The problem is that when trying to access either any of the auto-generated endpoints, or the custom endpoint custom, all I get is the HTML of the Meteor app itself (i.e. same as if I had navigated to the root URL of the app).
It is as if Restivus simply is not being run at all, yet a console.log at the end of the code block above verifies that it is at least being run. What am I doing wrong?
As I expected, it was something patently obvious. I am leaving this here just in case anyone else makes the same mistake.
The key is this line in the config:
version: 'v1'
this means that you will need to append /v1/ to your API path, so that the call itself has the format (for example):
mydomain.com/api/v1/myresource
I'm getting the error WARN [web-server]: 404: /app/workers/total.js when trying to run a unit test on a web worker.
Karma.conf.js includes the following:
...
files: [
...
'app/workers/*.js',
'unit-tests/mocks/**/*.js',
'unit-tests/src/**/*.js'
],
....
the test goes as follows:
describe('totals', function () {
var worker;
beforeEach(function() {
worker = new Worker('/app/workers/total.js');
});
it('should do something', function () {
...
});
});
I have tried many urls, but none seem to work
Finally I found the solution on https://github.com/karma-runner/karma/issues/1302, the trick is to include /base as part of the worker URL, being the solution:
describe('totals', function () {
var worker;
beforeEach(function() {
worker = new Worker('/base/app/workers/total.js');
});
it('should do something', function () {
...
});
});
Note /base as part of the worker URL.
Thanks to maksimr
I'm trying to make some basic tests on REST requests I'm doing using Angular $resource.
The service code works just fine.
'use strict';
angular.module('lelylan.services', ['ngResource']).
factory('Device', ['Settings', '$resource', '$http', function(Settings, $resource, $http) {
var token = 'df39d56eaa83cf94ef546cebdfb31241327e62f8712ddc4fad0297e8de746f62';
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token;
var resource = $resource(
'http://localhost:port/devices/:id',
{ port: ':3001', id: '#id' },
{ update: { method: 'PUT' } }
);
return resource;
}]);
I'm using the Device resource inside a directive and it works. The problems comes out
when I start making some tests on the services. Here is a sample test where I mock the
HTTP request using $httpBackend and I make a request to the mocked URL.
Unluckily it does not return anything, although the request is made. I'm sure about this
because if a request to another URL is made, the test suite automatically raises an error.
I've been spending lot of time, but no solutions. Here the test code.
'use strict';
var $httpBackend;
describe('Services', function() {
beforeEach(module('lelylan'));
beforeEach(inject(function($injector) {
var uri = 'http://localhost:3001/devices/50c61ff1d033a9b610000001';
var device = { name: 'Light', updated_at: '2012-12-20T18:40:19Z' };
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(uri).respond(device)
}));
describe('Device#get', function() {
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' });
expect(device.name).toEqual('Light');
}));
});
});
As the device is not loaded this is the error.
Expected undefined to equal 'Light'.
Error: Expected undefined to equal 'Light'.
I've tried also using the following solution, but it doesn't get into the function
to check the expectation.
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' }, function() {
expect(device.name).toEqual('Light');
});
}));
Any suggestion or link to solve this problem is really appreciated.
Thanks a lot.
You were very close, the only thing missing was a call to the $httpBackend.flush();. The working test looks like follows:
it('returns a JSON', inject(function(Device) {
var device = Device.get({ id: '50c61ff1d033a9b610000001' });
$httpBackend.flush();
expect(device.name).toEqual('Light');
}));
and a live test in plunker: http://plnkr.co/edit/Pp0LbLHs0Qxlgqkl948l?p=preview
You might also want to check docs for the $httpBackend mock.
In later versions of angular, I'm using 1.2.0rc1 you also need to call this within a $apply or call $digest on a scope. The resource call isn't made unless you do something like this:
var o, back, scope;
beforeEach(inject(function( $httpBackend, TestAPI,$rootScope) {
o = TestAPI;
back = $httpBackend;
scope = $rootScope.$new();
}));
it('should call the test api service', function() {
back.whenGET('/api/test').respond({});
back.expectGET('/api/test');
scope.$apply( o.test());
back.flush();
});