How to write an API test with Polymer iron-ajax - polymer

I am trying to generate an iron-ajax request and run a test on its response in Polymer 2.x with using the Mocha test suite.
However, when running this test I get the following error:
Cannot read property 'generateRequest' of undefined Context. at my-test.html:25
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>shop-catalogs</title>
<script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="/bower_components/web-component-tester/browser.js"></script>
<script src="/bower_components/web-component-tester/data/a11ySuite.js"></script>
<!-- Import the element(s) to test -->
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<script src="/bower_components/mocha/mocha.js"></script>
</head>
<body>
<test-fixture id="ajax">
<template>
<iron-ajax
handle-as="json"
headers$='{"Authorization": "Bearer api_access_token"}'
method="get"
url="https://api.com/test/endpoint">
</iron-ajax>
</template>
</test-fixture>
<script>
suite('shop-catalogs tests', () => {
var ajax;
test('checking for AJAX response', () => {
let request = ajax.generateRequest();
request.completes.then(response => {
console.log(response);
})
});
});
</script>
</body>
</html>
How can I make an AJAX request and handle the response in this framework?

I would advice to use fetch for this. It also will send an ajax call and is native to your browser.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>shop-catalogs</title>
<script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="/bower_components/web-component-tester/browser.js"></script>
<script src="/bower_components/web-component-tester/data/a11ySuite.js"></script>
<!-- Import the element(s) to test -->
<script src="/bower_components/mocha/mocha.js"></script>
</head>
<body>
<script>
suite('shop-catalogs tests', () => {
test('checking for AJAX response', (done) => {
fetch("https://api.com/test/endpoint", {
headers: {"Authorization": "Bearer api_access_token"}
}).then(res => {
assert.equal(res.status, 200)
return res.json()
})
.finally(res=>{
console.log(res)
done()//async test needs to tell when done
})
});
});
</script>
</body>
</html>

Related

window.MathJax is undefined?

Hi i Have a problem with MathJax library. I want to display the mathjax formula on the screen, but when I use window.MathJax I get the error that it is undefined. Here is how I installed the MathJax in my html file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<link rel="icon" href="/icons/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="/icons/favicon.ico" type="image/x-icon">
<!-- inject:css -->
<!-- endinject -->
<script type="text/x-mathjax-config">
MathJax = {
options: {
renderActions: {
addMenu: []
}
},
};
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<script async type="text/javascript" src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-svg.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>
<body>
<div id="application-content">
</div>
</body>
<!-- inject:js -->
<!-- endinject -->
<script type="application/javascript">
EMBED.default.init();
</script>
</html>
And here is the component where I use the library:
import React, { Component } from 'react';
export default class MathBlock extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
render() {
const text = this.props.block.getText();
const latexRegex = /\${2}(.*?)\${2}/;
const hasLatex = latexRegex.test(this.props.block.getText());
return (
<div>
<div
dangerouslySetInnerHTML={{
__html: hasLatex
? window.MathJax.tex2svg(text.replaceAll('$', '')).innerHTML
: window.MathJax.mathml2svg(text).innerHTML,
}}
/>
</div>
);
}
}
MathBlock.propTypes = {
block: React.PropTypes.object.isRequired,
};
Does anyone know what is the problem here?
Because the script tag that loads MathJax has the async attribute, it may not be loaded when your EMBED.default.init(); command likely will run before MathJax is loaded, and so before window.MathJax has been defined.
You could either remove the async attribute (which will mean your page will have to wait for MathJax to load and compile before the rest of the page is processed, slowing down your initial view of the page), or you could put the EMBED.default.init(); in MathJax's startup ready() function so that it is not performed until MathJax is loaded.
You are loading MathJax version 3, but your current configuration seems to be a mix of v2 and v3 configurations, and it is currently being ignored entirely by MathJax.
You could use
<script>
MathJax = {
options: {
renderActions: {
addMenu: []
}
},
tex: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
},
startup: {
ready() {
MathJax.startup.defaultReady();
EMBED.default.init();
}
}
};
</script>
(a correct v3 configuration) in place of your current configuration script, and see if that avoids the problem.

Problem with VUE.js not recognize vue component with intellij

I am writing because i have an issue using vue.js,
this is my index.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<h1> Prova VUE </h1>
<div id="app">
<p> Login:</p>
<button v-on : click="getInfo">OK</button>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
cordocs: [],
docenti: [],
link : '/newProvaTweb/hello-servlet'
},
methods:{
getInfo:function(){
var self = this;
$.get(this.link,{
action: "initialization"
}, function (data) {
self.cordocs = data[0];
});
}
}
});
</script>
I have included the script but, working with intellij doesn't recognize the vue component like this,
and it doesn't work. Someone know how to solve this problem?

Buttons in Cordova app for iOS platform doesn't work

I have a problem with my Cordova app.
Buttons in index.html work properly at first.
But, when I run my project several time, the buttons stop working.
They don't respond to being pressed.
One solution I read about suggested commenting out a line as shown:
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;"> -->
Unfortunately that didn't solve it.
index.html
<html><head><meta charset="utf-8" />
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;"> -->
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript"> app.initialize();</script>
</head>
<body onload="engage()">
<div class="app">
<h1>Hello</h1>
<div><button onclick="setDeviceAlias()">Set Device Alias</button></div>
<div><button onclick="getAlias()">Get Device Alias</button></div>
<div><button onclick="removeDeviceAlias()">Remove Device Alias</button></div>
</div>
</body>
index.js
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
document.addEventListener("resume", onResume, false);
app.receivedEvent('deviceready');
console.log('Received Event: ' + id);
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
function onResume() {}
function engage() {}
function setDeviceAlias() {
Plugin.setDeviceAlias("someAlias",
function (json) {
alert(JSON.stringify(json));
}, function (json) {
alert(JSON.stringify(json));
});
}
function getAlias() {
Plugin.getAlias(function (json) {
alert(JSON.stringify(json));
}, function (json) {
alert(JSON.stringify(json));
});
}
function removeDeviceAlias() {
Plugin.removeDeviceAlias("",
function (json) {
alert(JSON.stringify(json));
}, function (json) {
alert(JSON.stringify(json));
});
}

Cannot load CSS file from index.html

I understand that is was a frequently asked question. I looked at many other topics on stack overflow about it and I still don't know what the issue is? Some are saying it's because it's reading the file type as a text/html MIME type however I declared in my index.html it as text/css and it's still throwing me an error in the console.
And when i change it to text/html in my index file, the error in the console goes away but my styles won't load at all on my page even though the path is correct?
Error i get in console: localhost/:1 Refused to apply style from 'http://localhost:1234/assets/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I've been stuck trying to figure this out for past 2 hours I think it's something small I'm missing.
Here is my project structure:
INDEX.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../assets/css/styles.css">
<title>Portfolio Application</title>
</head>
<body>
<div id="app"></div>
<!-- Bootstrap JS Library -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" type="text/javascript" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" type="text/javascript" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript" src="bundle.js"></script></body>
</html>
Webpack.config file
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: __dirname + "/src/index.js",
output: {
path: __dirname + "/public",
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['env', 'react', 'stage-0']
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
]
}
Server file (Main.js)
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const app = express();
const port = 8010;
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(cors());
app.use(function(req, res, next){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
app.use('/', express.static(__dirname + "/../public"));
app.listen(port, () => {
console.log(`app is listening in on port ${port}`);
});
Folder structure:
root
public (folder)
assets
fonts
images
bundle.js
index.html
server (folder)
main.js
src (folder)
common (folder)
components (folder)
index.js
routes.js
package.json
webpack.config.js

Ng-view or ui-view not displaying html page

I am relatively new to Angularjs, and am building a website. When I try to inject todo.html into the body tags of index.html nothing happens. I am not getting any errors in the console. I have read many of the similar posts to mine, and have already tried
Remove the ng-include from the body of index.html
Moved the links for angualrjs and bootstrap from the body of index.html to the head
Originally I used Ng-route but it did not work, so I implemented ui-router
I have tried both ng-route and ui-router,and both run without any errors. I don't think it has anything to do with either.
index.html
<html ng-app="todoApp">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Todo App</title>
<!-- Angular ans JS links-->
<script src="vendor/angular/angular.min.js"></script>
<script src="vendor/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="app/app.js"></script>
<script src="app/services/todo.service.js"></script>
<script src="app/controllers/todo.controller.js"></script>
<!-- <script src="vendor/angular-route/angular-route.min.js"></script>-->
<!--Jquery and Bootstrap Links-->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js" integrity="sha384-VjEeINv9OSwtWFLAtmc4JCtEJXXBub00gtSnszmspDLCtC0I4z4nqz7rEFbIZLLU"
crossorigin="anonymous"></script>
<!-- css links -->
<link href="vendor/bootstrap-css-only/css/bootstrap.min.css" rel="stylesheet"><!-- load bootstrap -->
<link rel="stylesheet" href="assets/css/todoApp.css">
<link rel="stylesheet" type="text/css" href="assets/css/Header-Picture.css">
</head>
<body >
<div ng-include="'app/views/header.html'"></div>
<!--<div ng-include="'app/views/footer.view.html'"></div>
-->
<ui-view></ui-view>
<!--<div ui-view></div>-->
</body>
</html>
App.js
var todoApp = angular.module('todoApp', [
'ui.router'
]);
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'views/todo.html',
controller: 'TodoController'
})});
todo.controller.js
todoApp.controller('TodoController', ['$scope', 'Todos', function TodoController($scope, Todos) {
$scope.formData = {};
console.log("in the TodoController");
// when landing on the page, get all todos and show them
Todos.get()
.success(function(data) {
$scope.todos = data;
});
// when submitting the add form, send the text to the spring API
$scope.createTodo = function() {
if(!$scope.todoForm.$valid) {
return;
}
Todos.create($scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos.push(data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
Todos.delete(id)
.success(function(data) {
angular.forEach($scope.todos, function(todo, index){
if(todo.id == id) {
$scope.todos.splice(index, 1);
}
});
});
};
// when submitting the add form, send the text to the node API
$scope.saveTodo = function(todo) {
Todos.update(todo)
.success(function(data) {
$scope.editedTodo = {};
});
};
$scope.editedTodo = {};
$scope.editTodo = function(todo) {
$scope.editedTodo = todo;
}
$scope.revertTodo = function() {
$scope.editedTodo = {};
}
}]);
You should be using otherwise to force the first state to be loaded as below
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'todo.html',
})
$urlRouterProvider.otherwise('/');
});
Your index.html will look like
<div ng-include="'app/views/header.html'"></div>
<ui-view>
</ui-view>
LIVE DEMO
I added the code posted by #Aravind to my project which I belive was an improvement on my own and was correct. But the issue was the file path to the todo.html. The file path in the original was views/todo.html
the correct path is app/views/todo.html
My original code:
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'views/todo.html',
controller: 'TodoController'
})});
Current Working Code
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'app/views/todo.html',
})
$urlRouterProvider.otherwise('/');
});