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.
Related
How to fetch Laravel multiple return "array" data in Vuejs
Below Laravel code is working properly.
public function show($id)
{
$model = Fabricsbooking::with(['fileno','fileno.merchandiser', 'fileno.buyer', 'items.yarncount'])
->findOrFail($id);
$yarn = Fabricsbookingitem::with('yarncount')->where('fabricsbooking_id', $id)
->groupBy('yarncount_id')
->selectRaw('sum(qty)as yarn_qty, sum(total_yarn)as total_yarn, yarncount_id' )
->get();
return Response::json(array(['model'=>$model],['yarn'=> $yarn]));
}
api.js code
import axios from 'axios'
export function get(url, params) {
return axios({
method: 'GET',
url: url,
params: params,
})
}
export function byMethod(method, url, data) {
return axios({
method: method,
url: url,
data: data
})
}
Vue template page script:
<script>
import Vue from 'vue'
import {get, byMethod} from '../../lib/api'
export default {
data:()=>{
return{
show:false,
model:{
items:[],
fileno:{},
},
yarn:{}
}
},
beforeRouteEnter(to, from, next){
get(`/fabbooking/${to.params.id}`)
.then((res)=>{
next(vm=> vm.setData(res))
})
},
beforeRouteUpdate(to, from, next){
this.show = false
get(`/fabbooking${to.params.id}`)
.then((res)=>{
this.setData(res)
next()
})
},
methods:{
setData(res){
Vue.set(this.$data, 'model', res.data.model)
this.show=true
},
deleteItem(){
byMethod('delete', `/fabbooking/${this.model.id}`)
.then((res)=> {
if (res.data.deleted){
this.$router.push('/fabook')
}
})
}
},
}
</script>
When load the page in browser, shown below error code in Console
"app.js:682[Vue warn]: Error in render: "TypeError: Cannot read property 'id' of undefined""
Need to solutions for Vue template page script.
The problem here is Cannot read property 'id' of undefined
Since the only place you use id is in to.params.id it means that params is undefined.
You can double check it with the following test:
beforeRouteEnter(to, from, next){
console.log(to.params)//like this you check params has values.
},
Maybe your route is not correctly configured. Did you forget the "props:true" flag for example?
More info in the docs: vue route params
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
Let's say you have an AngularJS application hooked up to a RESTful API and you have a route for "/item/:itemId".
.when('/item/:itemId', {
templateUrl: '/static/partials/item-detail.html',
controller: ItemDetailController
})
angular.module('angServices', ['ngResource']).factory('Item', function($resource) {
return $resource('/api/item/:itemId', {}, {
query: { method: 'GET', params: { itemId: '' }, isArray: true }
});
});
If the user goes to "/item/9" and an object with the itemId 9 does not exist, Angular will receive a 404 from the API, but will not naturally return a 404 to the user.
In other questions, I've seen people suggest creating an interceptor and having Angular redirect to a 404 error page when a resource is not found.
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
However, I want to return a correct 404 with the original requested URL for SEO purposes.
Also, the solution above first loads the page and then redirects (just like Twitter used to do), so its sub-optimal.
Should I check server-side to first see if the resource exists before passing the request on to the Angular app? The downside of this is that it wouldn't work for broken links within the application.
What is the best way to approach this?
Maybe this jsfiddle can help you.
http://jsfiddle.net/roadprophet/VwS2t/
angular.module('dgService', ['ngResource']).factory("DriveGroup", function ($resource) {
return $resource(
'/', {}, {
update: {
method: 'PUT'
},
fetch: {
method: 'GET',
// This is what I tried.
interceptor: {
response: function (data) {
console.log('response in interceptor', data);
},
responseError: function (data) {
console.log('error in interceptor', data);
}
},
isArray: false
}
}
);
});
var app = angular.module('myApp', ['ngResource', 'dgService']);
app.controller('MainController', ['$scope', 'DriveGroup', function ($scope, svc) {
$scope.title = 'Interceptors Test';
svc.fetch(function (data) {
console.log('SUCCESS');
}, function () {
console.log('FAILURE');
});
}]);
I tried with this and works fine. I only change the fetch method to get.
In your case, you will need to change the console.log('FALIURE'); to $location.path('/404');.
GL!
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();
});
I keep getting "undefined is not a function" when calling the factory. I am using the angular-seed as the framework for my setup. For some reason, it doesn't recognize "GetFormVals" as a valid factory.
In app.js:
var app = angular.module('myApp', ['myApp.filters',
'myApp.services', 'myApp.directives'], function($routeProvider, $locationProvider) {
//route declarations
$routeProvider.when('/fsr', {
templateUrl: 'partials/fsr.html',
controller: ctrlFSR
});
$locationProvider.html5Mode(true);
});
In controllers.js:
function ctrlFSR($scope, $http, $location, GetFormVals) {
$scope.test = GetFormVals();
}
ctrlFSR.$inject = ['$scope','$location'];
In services.js:
'use strict';
/* Services */
angular.module('myApp.services', []).
factory('GetFormVals', function(){
return "test";
});
I have to be missing something simple.
jsfiddle: http://jsfiddle.net/wUjw5/11/
You need to list all the dependencies to be injected into your controller:
function ctrlFSR($scope, $http, $location, GetFormVals) {
$scope.test = GetFormVals();
}
ctrlFSR.$inject = ['$scope', '$http', '$location', 'GetFormVals'];
Change your service to this
'use strict';
/* Services */
angular.module('myApp.services', []).
factory('GetFormVals', function(){
return {
exampleValue: "test5"
}
});
Then in your controller you would update it to this:
function ctrlFSR($scope, $http, $location, GetFormVals) {
$scope.test = GetFormVals.exampleValue;
}
ctrlFSR.$inject = ['$scope','$location'];
I think the confusion came in with you calling GetFormVals as a function, while in reality it's a service.
jsfiddle: http://jsfiddle.net/rtCP3/49/
your js fiddle modified http://jsfiddle.net/wUjw5/12/
Don't inject with ctrlFSR.$inject = ['$scope','$location'];. You already are.