How to compare only output part in html and javascript? - javascript

I have a plan to create an app for JavaScript test. In here I will give a question for creating a program, for example, show the text "HTML Code Play" in alert box? The user will do the coding, and they can use any name for the functions, variable, etc.
I want to check the output, where the output show the alert box "HTML Code Play".
User Code
<script>
function showalert()
{
alert("HTML Code Play");
}
</script>
<input type="button" value="Show Alert" onclick="showalert();">
Compare with the following code(My code)
<button onclick="alertbox();">Show Alert</button>
<script>
function alertbox()
{
alert("HTML Code Play");
}
</script>
In the examples above, both produce the same output but the coding is different.
When I check both codes, I want the result true. Can I do it? Is it possible?

I found your question interesting, and created sample code using mocha and sinon.
(To exec this, you must install sinon.js modules by yourself.)
I published this code here as working code.
Please regard 'code1','code2' blocks as user-implemented codes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to test user code on broweer</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.css" rel="stylesheet">
<script type="text/javascript" src="../components/sinon/lib/sinon.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/util/core.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/extend.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/spy.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/call.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>How to test user code on broweer</h1>
<div id="mocha"></div>
<div id="live-code-stage"></div>
<template id="code1">
<button onclick="alertbox();">Show Alert</button>
<script>
function alertbox() {
alert("HTML Code Play");
}
</script>
</template>
<template id="code2">
<script>
function showalert() {
alert("HTML Code Play");
}
</script>
<input type="button" value="Show Alert" onclick="showalert();">
</template>
</div>
<script>
mocha.setup('bdd');
$(function () {
var assert = function (expr, msg) {
if (!expr) throw new Error(msg || 'failed');
};
describe("implement 'show alert button' test", function () {
before(function () {
window.alert = sinon.spy();
});
it("window.alert must to be called with 'HTML Code Play'", function (done) {
$("#live-code-stage").html($("#code1").html()); // testing code1
$("button, input[type='button']").click();
assert(window.alert.calledWith("HTML Code Play"));
done();
});
});
mocha.run();
});
</script>
</body>
</html>
Key Points
You can mock 'window.alert' like this:
window.alert = sinon.spy();
And you can check if it(=alert) was called with correct argument like this:
assert(window.alert.calledWith("HTML Code Play"));
If user-created code is wrong, mocha test will fail.
Introducing qunit may improve the test report appearance.
But this is just a sample. There must be many options to archive what you want.

Related

How to call Jquery Plugin function from outside of plugin

I am using asp.net mvc application.
From last 2 days i am trying and following some Internet solutions to call the MyPlugin function from outside the JS .
Please help me to find what wrong i am doung.
I had added myplugin JS and written some lines of code and now i am trying to access that function from View script.
My View :
<head>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/MyPlugin.js"></script>
</head>
<body>
<div id="divMain" >
</div>
</body>
<script>
$(document).ready(function () {
$("#divMain").MyPlugin();
});
</script>
MyPlugin JS:
(function ($) {
$.fn.MyPlugin= function () {
alert("ready to start!!!!");
};
})(jQuery);
And This message i got :
"Uncaught TypeError: $(...).MyPlugin is not a function"
Please help me to find a solution of this problem. I want to call that Plugin's function.
You have to add jquery prior to your plugin js.
<head>
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/MyPlugin.js"></script>
</head>
<body>
<div id="divMain" >
</div>
</body>
<script>
$(document).ready(function () {
$("#divMain").MyPlugin();
});
</script>

Underscore method _.template() doesn't compile my template

I'm getting started with backbone.js and i want to build a template, containing only a html button, with my model attributes. So I defined a template in my html page as below:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Backbone test 5</title>
<script src="underscore.js"></script>
<script src="jquery.js"></script>
<script src="backbone.js"></script>
<script src="backbone_test5.js"></script>
</head>
<body>
<div id="here"></div>
<script type="text/template" id ="button_template">
<button type="button" id="my_button"><%= text %></button>
</script>
</body>
</html>
and I'm trying to build my template in my view:
var Bouton_View= Backbone.View.extend({
view_template: _.template( $('#button_template').html() ),
events:{
'click':'onClick'
},
initialize: function(){
this.$el=('#here');
},
render: function(){
this.$el.html(this.view_template(this.model.attributes));
return this;
},
onClick: function(){
var increment=0;
increment=this.Model.get("number_of_click")+1;
this.Model.set({"text":increment});
this.Model.set({"number_of_click":increment});
this.render();
}
});
but when I run the page in the browser this error message show up:
I'm pretty sure the js file is not wrong because I've try this with another html file and it worked. So what is wrong with my template? thanks in advance
Why so?
Spoiler: the underscore templating engine is fine in this case.
This example's problem is that the code which describes your Bouton_View, which probably lies here:
<script src="backbone_test5.js"></script>
is executed before the DOM parser reaches
<script type="text/template" id ="button_template">
<button type="button" id="my_button"><%= text %></button>
</script>
element. This can be described as
Load backbone_test5.js file and execute its contents
Execute _.template( $('#button_template').html() )
Search DOM for element with id="button_template"
None found
Execute .html() function on a non-existent $ element => this results in null
Execute _.template(null) => this gives you the error you mentioned
How to fix?
There are several ways to do that.
HTML-only. Re-order the code so that DOM elements exist when queried:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Backbone test 5</title>
</head>
<body>
<div id="here"></div>
<script type="text/template" id ="button_template">
<button type="button" id="my_button"><%= text %></button>
</script>
<script src="underscore.js"></script>
<script src="jquery.js"></script>
<script src="backbone.js"></script>
<script src="backbone_test5.js"></script>
</body>
</html>
With some js-code. You can wrap the contents of the backbone_test5.js file with the $(...) so that it only executes once the DOM content is ready:
$(function () {
var Bouton_View = Backbone.View.extend({ /* ... */ });
});

JavaScript function called with button onclick, fails with onload

I am trying to use an external JavaScript function in the body tag: <body onload=function()>
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<script type="text/javascript" src="js/mqttws31.js"></script>
<script type="text/javascript" src="js/Long.min.js"></script>
<script type="text/javascript" src="js/ByteBufferAB.min.js"></script>
<script type="text/javascript" src="js/ProtoBuf.min.js"></script>
<script type="text/javascript" src="js/fs.js"></script>
<script type="text/javascript" src="js/bundle.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="cordova_plugins.js"></script>
</head>
<body onload ="heartbeat()">
<h2>A demo for showing the pub/sub between clients and the message broker</h2> <h3>IoTGateway</h3>
Topic :
<input type="text" name="pub"/>
Message:
<input type="text" name="pub"/>
<button onclick="connect()">
Connect
</button>
<br>
<button onclick="publish()">
Publish
</button>
<br>
<h3>BluetoothID</h3> Topic:
<input type="text" name="sub"/>
<button onclick="heartbeat()">
Subscribe
</button>
<br>
<p id = "test"></p>
<p id="sub"></p>
<script>
function heartbeat() {
alert("hello");
try{
MqttPlugin.subscribe({topic: "$EDC/plugin"});
}
catch(err){
alert(err.message);
}
}
/* try{
MqttPlugin.heartbeat({topic: "$EDC/tum/B8:27:EB:A6:A9:8A/HEARTBEAT-V1/mqtt/heartbeat"});
}
catch(err){
alert(err.message);
}*/
function publish() {
MqttPlugin.publish({
topic:"$EDC/plugin",
data:"Mqtt data"
});
}
function subscribe() {
MqttPlugin.subscribe({topic: "$EDC/plugin"});
}
</script>
</body>
</html>
The function heartbeat is called when I call with the event onclick but fails with onload. In case of onload, it throws an error MqttPlugin not defined. Is it because by the time it calls the function, the js files are not loaded? Could someone help me fix this?
I believe that your basic aim here is to subscribe to a topic automatically when the page is loaded. You can either try:
</script>
<style onload="heartbeat()"></style>
</body>
Or try changing the order of imports.
The first suggestion is just an hack not a full proof solution though.
The basic problem is that the heartbeat function is getting called before cordova_plugins.js is getting loaded. So either delaying the function call or loading the file early will do the trick.
Edited:
This jQuery method might just be the solution:
$( window ).load()
Please find documentation here.

jasmine-jQuery, How to test for form fill out and change of HTML element?

I am trying to test for the filling out of an HTML form and the subsequent change of an HTML elements Text. I need to create some form of event using jasmine-jquery...
HTML
<div class="response" id="text-response">Unknown</div>
<div class="form-holder">
<form>
<input id="input-text" type="text" name="user-input" placeholder="Test Your Text" value="">
<input id="submit-button" type="submit" value="Submit">
</form>
</div>
I am trying to test drive id='text-response' changing to 'Correct' based on some script logic.
describe('Interface logic', function(){
it('Will return correct if logic applies', function(){
expect('#emotion').toContainText('Correct');
});
});
Any help would be much appreciated
You might just need to trigger an event, for example:
$('#submit-button').click();
That should fire the click event. Then you can check for whatever condition this event changes on the page.
$('#submit-button').click();
Was the solution for me but the spec runner constant refresh is because you're hitting http://localhost:3000/specs/ rather than http://localhost:3000/SpecRunner.html
If you have your form html in a separate template in a file named for example
templates/form.tmpl.html
and your jquery in a separate file also named for example
js/validation.js
And containing validation code like
$(".form-holder").on("submit", function() {
event.preventDefault();
var userInput = $('#input-text').val();
if (userInput === 'the correct text') {
$('#text-response').text('Correct');
return;
}
$('#text-response').text('Incorrect');
});
Then your test spec can be something similar to this
describe('Interface logic', function() {
jasmine.getFixtures().fixturesPath = '';
beforeEach(function() {
loadFixtures('templates/form.tmpl.html');
appendSetFixtures('<script src="js/validation.js"></script>')
});
it('Will return correct if logic applies', function(){
$('#input-text').val('the correct text');
$('#submit-button').trigger("click");
expect($('#text-response').text()).toBe('Correct');
});
it('Will return incorrect if logic applies', function(){
$('#input-text').val('the incorrect text');
$('#submit-button').trigger("click");
expect($('#text-response').text()).toBe('Incorrect');
});
});
And the spec runner html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spec Runner</title>
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.3/jasmine.css">
<script type="text/javascript" src="lib/jasmine-2.0.3/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.3/jasmine-html.js"></script>
<script src="lib/jasmine-2.2/boot.js"></script>
<script type="text/javascript" src="lib/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="lib/jasmine-jquery.js"></script>
<script type="text/javascript" src="specs/form.spec.js"></script>
</head>
<body>
</body>
</html>

javascript ReferenceError on onclick

<html>
<head>
<script>
function view_more(pg_no){
alert(pg_no);
}
</script>
</head>
<body>
<span onClick="view_more('1')"></span>
</body>
</html>
Here, I can't understand why it say always
[ReferenceError: view_more is not defined]
I got the same problem today.
My situation was like this:
.html file:
<head>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
</head>
<body>
<div class="lc-form-holder">
<form action="#" method="post">
[...]
<span onclick="myFunction();">NEXT</span>
</form>
</div>
</body>
and .js file:
$(document).ready(function() {
function myFunction() {
console.log('click click');
}
});
When I clicked on <span> I got an error Uncaught ReferenceError: myFuncion is not defined.
But when I do this in .js file (no document.ready):
function myFunction() {
console.log('click click');
}
Everything work just fine.
I don't know is this helpful but I wanna share it if someone check this question in future.
Try this first
<body>
<span onClick="alert('1');"></span>
if the above code works then there must exists others javascript which are actually got error prior to execute your code.
<span onClick="view_more('1')">Test</span>
Add text and then click on text
Working at my end
This is my code --
<html>
<head>
<script>
function view_more(pg_no){
alert(pg_no);
}
</script>
</head>
<body>
<span onClick="view_more('1')">gfgf</span>
</body>
</html>
EDIT
try using this code --
<html>
<head>
<script type="text/javascript">
function view_more(pg_no)
{
alert(pg_no);
}
</script>
</head>
<body>
<span onClick="javascript:view_more('1');">gfgf</span>
</body>
</html>

Categories